我在嘗試學習Python並且通過https://automatetheboringstuff.com/chapter14/上的一些示例工作 - 這是一個拉取簡單天氣數據的例子。我在運行腳本時遇到了一個錯誤,我似乎無法找到...小學的答案,因爲我不知道該如何提問,所以在這裏:TypeError:並非在字符串格式化過程中轉換的所有參數 - Python
我的代碼(來自圖書)
#! python3
# quickWeather.py - Prints the weather for a location from the command line
import json
import requests
import sys
# Compute location from command line arguments.
if len(sys.argv) < 1:
print('Usage: quickweather.py location')
sys.exit()
location = ' '.join(sys.argv[1:])
# Todo: Download the json data from OpenWeatherMap.org's API
url = 'http://api.openweathermap.org/data/2.5/forecast/city?id=5391811&APPID=5103aa7d5415db6xxxxxxxxxxxxxxx' % (location)
response = requests.get(url)
response.raise_for_status()
# Load JSON data into Python variable.
weatherData = json.loads(response.text)
w = weatherData['list']
print('Current weather in %s:' % (location))
print(w[0]['weather'][0]['main'], '-', w[0]['weather'][0]['description'])
print()
print('Tomorrow:')
print(w[1]['weather'][0]['main'], '-', w[1]['weather'][0]['description'])
print()
print('Day after tomorrow:')
print(w[2]['weather'][0]['main'], '-', w[2]['weather'][0]['description'])
和我的控制檯錯誤
[email protected]_tests $ python3 quickWeather.py
Traceback (most recent call last):
File "quickWeather.py", line 16, in <module>
url = 'http://api.openweathermap.org/data/2.5/forecast/city?id=5391811&APPID=5103aa7d5415db6xxxxxxxxxxxxxxxx' %(location)
TypeError: not all arguments converted during string formatting
如果我從URL路徑刪除%(位置),控制檯將打印數據除了位置,在這種情況下是聖地亞哥。
我知道這只是一個小問題,如果我對Python有更多的瞭解,那很容易回答,但現在,在弄了兩個小時之後,我很想知道它到底是什麼。
謝謝你的幫助。
那麼在字符串應該插入位置的位置?你缺少一個'%s'佔位符。 –
'%'字符串格式化的工作方式是你必須在你的字符串中爲你的元組中的每個值設置一個'%x'的佔位符。 –
%在第一個打印語句中...這本書稍微有一點(對於初學者),因爲它甚至沒有提到需要API密鑰,但這裏是完整的字符串與我的APIKEY(我可以稍後重置) - (位置)應該抓住城市名稱...只需將其粘貼到您的瀏覽器中即可http://api.openweathermap.org/data/2.5/forecast/city?id=5391811&APPID=5103aa7d5415db68faab1777de2897ee –