Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in Python Loop

Tags:

python

regex

Trying to scrape weather condition (index 9 in list v) and save the variable for later. Having difficulty writing the proper regex to store condition that is either 1 or 2 words.

Tested my regex code on regexr.com and it looks fine but doesn't work when run in IDLE.

v = ['\n\n7:53 AM\n\n\n\n\n',
 '\n\n\n\n\n\n48 \nF\n    \n\n\n\n\n\n\n',
 '\n\n\n\n\n\n45 \nF\n    \n\n\n\n\n\n\n',
 '\n\n\n\n\n\n89 \n%\n    \n\n\n\n\n\n\n',
 '\n\nSE\n\n\n\n\n',
 '\n\n\n\n\n\n5 \nmph\n    \n\n\n\n\n\n\n',
 '\n\n\n\n\n\n0 \nmph\n    \n\n\n\n\n\n\n',
 '\n\n\n\n\n\n30.11 \nin\n    \n\n\n\n\n\n\n',
 '\n\n\n\n\n\n0.0 \nin\n    \n\n\n\n\n\n\n',
 '\n\nMostly Cloudy\n\n\n\n\n']

for condition in str(v[9]):
        condition_search = re.findall('[A-Z]\w+', condition)
        if len(condition_search) > 1:
            condition = ' '
            condition = condition.join(condition_search)
        else:
            condition = str(condition_search)

print(condition)

actual results:

'[]'

desired results

'Mostly Cloudy'
like image 303
Amocat _ Avatar asked Apr 14 '26 18:04

Amocat _


1 Answers

Regexps are nice, but I think you are looking for .strip():

text='\n\nMostly Cloudy\n\n\n\n\n'
print(text.strip())

Result:

Mostly Cloudy

and the surrounding whitespace is gone.
(Find docs on https://docs.python.org/3/library/stdtypes.html)

like image 109
tevemadar Avatar answered Apr 16 '26 09:04

tevemadar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!