简体   繁体   English

从Python中的变量中删除字符

[英]Removing characters from a variable in Python

I've been using the weather site Open Weather Map ( https://openweathermap.org/ ) to get details for a project 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

And then insert them the variables into a database, which doesn't like '{' '}'. 然后将变量插入到不喜欢'{''}'的数据库中。

I've tried removing the '{' '}' from the outputs, looking at replies from this site. 我尝试从输出中删除'{''}',并查看此站点的回复。 Strip: 跳闸:

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

and Replace: 并替换:

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

But all I'm getting are "AttributeError: 'dict' object has no attribute". 但是我得到的只是“ AttributeError:'dict'对象没有属性”。 Is there another escape clause I could use for the variable to remove the unwanted characters? 我是否可以使用另一个转义子句来删除变量中不需要的字符?

How to use string.replace() in python 3.x 如何在python 3.x中使用string.replace()

How to remove certain characters from a variable? 如何从变量中删除某些字符? (Python) (蟒蛇)

A python dictionary is returned and you need to access the key and value instead of removing the {}. 返回一个python字典,您需要访问键和值,而不是删除{}。 The following shows how to access dictionary values. 下面显示了如何访问字典值。

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

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

Since your variable is a dict , you'll need to create a suitable string representation of it. 由于您的变量是dict ,因此您需要为其创建合适的字符串表示形式。 You can concatenate the keys and values with your own formatting like so: 您可以使用自己的格式将键和值连接起来,如下所示:

# a: 1, b: 2, c: 3
myString = ', '.join('{}: {}'.format(k, v) for k,v in myDict.items())

Or modify the default string representation returned by str 或修改str返回的默认字符串表示形式

# 'a': '1', 'b': '2', 'c': '3'
myString = re.sub('[{}]', '', str(myDict));

first of all you need to know what type of data you get: 首先,您需要知道获得的数据类型:

print (type(obj))

and this is not a string, you can't replace any symbols. 这不是字符串,您不能替换任何符号。

one more. 多一个。 if you get info from site as like json-object, so you don't need replace anything because you can use key for parsing info and, if you need, write to database 如果您像json-object这样从站点获取信息,则无需替换任何内容,因为您可以使用key来解析信息,并在需要时写入数据库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM