简体   繁体   中英

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.

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". 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

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 {}. 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. 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

# '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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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