Phil
Phil

Reputation: 103

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)

Upvotes: 0

Views: 1211

Answers (3)

Konstantin Kozlenko
Konstantin Kozlenko

Reputation: 186

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

Upvotes: 0

jspcal
jspcal

Reputation: 51914

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));

Upvotes: 0

tda
tda

Reputation: 2133

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

Upvotes: 3

Related Questions