我在尝试学习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 –