Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a list of strings to use them in a condition?

Tags:

python

source = open("file1")    
out = open("file2", "w")

days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']

for line in source:
    out.write(line)
    if line.startswith('HERE IS WHERE I WOULD LIKE THE DAYS TO BE LOOPED'):
        break    
out.close()
like image 813
ashleh Avatar asked Dec 21 '22 07:12

ashleh


1 Answers

Looking at help(str.startswith), you can see that the method accepts a tuple of strings to search for, so you can do it all in one step:

>>> 'Mon is the first day'.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'))
True

Here is a variant that runs on older versions of Python:

>>> import re
>>> days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
>>> pattern = '|'.join(days)
>>> if re.match(pattern, 'Tue is the first day'):
        print 'Found'

Found
like image 60
Raymond Hettinger Avatar answered Feb 15 '23 23:02

Raymond Hettinger