【问题标题】:TypeError: not all arguments converted during string formatting - PythonTypeError:字符串格式化期间并非所有参数都转换 - Python
【发布时间】:2015-11-07 03:54:56
【问题描述】:

我正在尝试学习 Python 并且正在研究https://automatetheboringstuff.com/chapter14/ 上的一些示例——这个是提取简单的天气数据。运行脚本时出现错误,我似乎无法找到...主要的答案,因为我不知道如何询问它,所以这里是:

我的代码(来自书中)

#! 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'])

我的控制台错误

rooster@python_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 有更多的了解,那将很容易回答,但现在,经过 2 个小时的研究,我很想知道到底发生了什么。

感谢您的帮助。

【问题讨论】:

  • 那么应该在字符串的哪个位置插入位置?您缺少 %s 占位符。
  • % 字符串格式化的工作方式是,您必须在字符串中为元组中的每个值添加一个 %x 占位符。
  • % 在第一个打印语句中......这本书有点偏离(对于初学者),因为它甚至没有提到需要 API 密钥,但这是我的完整字符串APIKEY(我可以稍后重置)-(位置)应该获取城市名称...只需将其粘贴到浏览器中即可api.openweathermap.org/data/2.5/forecast/…

标签: python


【解决方案1】:

% 字符串格式化功能使用占位符;每个内插值都会替换其中一个占位符。您的字符串中没有包含任何占位符,因此 Python 无法知道将 location 的值放在哪里。

如果您想创建一个forecast for a location,您需要包含一个q=place,country 参数。您链接到的页面正是这样做的,使用 %s 占位符:

url ='http://api.openweathermap.org/data/2.5/forecast/daily?q=%s&cnt=3' % (location)

这里将location 字符串值插入到%s 位置的URL 中。

【讨论】:

  • 啊……我想我明白了……让我快速实验一下,我会告诉你的。谢谢。
猜你喜欢
  • 2015-10-28
  • 2013-10-21
  • 2017-08-13
  • 2020-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-23
相关资源
最近更新 更多