[英]Removing characters from a variable in 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字典,您需要訪問鍵和值,而不是刪除{}。 下面顯示了如何訪問字典值。
print(rain.keys()) # returns a list of all dictionary keys
>>> ['3h']
print(rain['3h']) # returns the value associated with the '3h' key
>>> 0
由於您的變量是dict
,因此您需要為其創建合適的字符串表示形式。 您可以使用自己的格式將鍵和值連接起來,如下所示:
# a: 1, b: 2, c: 3
myString = ', '.join('{}: {}'.format(k, v) for k,v in myDict.items())
或修改str
返回的默認字符串表示形式
# 'a': '1', 'b': '2', 'c': '3'
myString = re.sub('[{}]', '', str(myDict));
首先,您需要知道獲得的數據類型:
print (type(obj))
這不是字符串,您不能替換任何符號。
多一個。 如果您像json-object這樣從站點獲取信息,則無需替換任何內容,因為您可以使用key來解析信息,並在需要時寫入數據庫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.