Ryan Werner
Ryan Werner

Reputation: 187

How to isolate a certain part of a string and print it?

I'm using the pyowm module to scrape weather data from OpenWeatherMap. It works fine, but when I request the weather, it outputs it in this format

<pyowm.webapi25.weather.Weather - reference time=2015-10-28 18:01:16+00, status=rain>

is there a to, for example, grab the words "rain" or "cloudy" by assigning the letters between the "=" and closing tag(>) to a new variable and then printing this new variable?

Upvotes: 0

Views: 120

Answers (3)

NPE
NPE

Reputation: 500167

You don't need to parse the string to get the data you want. What you currently have is an object of type pyowm.webapi25.weather.Weather. You can access its fields like so:

print weather_obj.get_reference_time()
print weather_obj.get_status()

(where weather_obj is the name of your object.)

The the documentation for further information.

Upvotes: 1

Flying_Banana
Flying_Banana

Reputation: 2910

You can find the index of the last occurrence of "=" and ">" by calling:

lastEqualIndex = weatherString.rfind("=")
lastLTIndex = weatherString.rfind(">")

Then what you want is just:

weather = weatherString[lastEqualIndex + 1, lastLTIndex]

Upvotes: 0

vks
vks

Reputation: 67968

import re
x="<pyowm.webapi25.weather.Weather - reference time=2015-10-28 18:01:16+00, status=rain>"
print re.findall(r"(?<==)[^=]*(?=>)",x)

You can use re with lookbehind for this.

Upvotes: 0

Related Questions