首页 > 解决方案 > 从 Python 中的变量中删除字符

问题描述

我一直在使用天气网站 Open Weather Map ( https://openweathermap.org/ ) 来获取 Python 项目的详细信息。

rain = w.get_rain() # Get rain volume {'3h': 0} 
wind = w.get_wind() # Get wind degree and speed {'deg': 59, 'speed': 2.660}
humidity = w.get_humidity() # Get humidity percentage 67

然后将它们插入到不喜欢'{''}'的数据库中。

我已经尝试从输出中删除“{”“}”,查看来自该站点的回复。跳闸:

rain = rain.strip(['{','}'])

并替换:

rain = rain.replace('{', ' ')

但我得到的只是“AttributeError:'dict'对象没有属性”。是否有另一个转义子句可以用于变量以删除不需要的字符?

如何在 python 3.x 中使用 string.replace()

如何从变量中删除某些字符?(Python)

标签: python

解决方案


返回一个 python 字典,您需要访问键和值而不是删除 {}。下面显示了如何访问字典值。

print(rain.keys()) # returns a list of all dictionary keys
>>> ['3h']

print(rain['3h']) # returns the value associated with the '3h' key
>>> 0

推荐阅读