user61629 user61629 -4 years ago 79
Python Question

How to use the 'any()' function to search for multiple substrings?

I have the following code where I am trying to open a textfile, read through it line by line, and if a line has a certain country code (

US
,
BR
), add it to a list
myNames
:

f = urllib2.urlopen(url)
countries = ['US', 'BR']
myNames = []
for line in f:
line = f.readline()
if any(x in line for x in countries):
myNames.append(line)


Unfortunately I think my use of
any()
must be incorrect because it is yielding only a small number from 1 country and none from the second even though I can verify that there are more of each type. How can I fix this?

Answer Source

It's hard to say without knowing what x is and what's in the file, but this snippet:

for line in f:
    line = f.readline()

is reading two lines at a time -- for line in f is already iterating over the file line by line, by reading twice you're skipping every other line. That would explain why you're getting too few results.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download