简体   繁体   中英

Having problems with the Python IN Operator

I am trying to match a string of text in a list with the in operator. All I get is a false response, even though the string is in the list.

[File ASpaceOdyssey.txt]

Behind every man now alive stand thirty ghosts, for that is the ratio by which the dead outnumber the living. Since the dawn of time, roughly a hundred billion human beings have walked the planet Earth.

Now this is an interesting number, for by a curious coincidence there are approximately a hundred billion stars in our local universe, the Milky Way. So for every man who has ever lived, in this Universe there shines a star.

'This day is not yet available'


But every one of those stars is a sun, often far more brilliant and glorious than the small, nearby star we call the Sun. And many - perhaps most - of those alien suns have planets circling them. So almost certainly there is enough land in the sky to give every member of the human species, back to the first ape-man, his own private, world-sized heaven - or hell.

My code:

Testdata = open('C:/ASpaceOdyssey.txt').readlines()  
'This day is not yet available' in Testdata

False

"'This day is not yet available'" in Testdata

False

"This day is not yet available" in Testdata

False

testdata is a list of strings, not a single string. But the way you test with the in operator is substring in string .

So you need a list-comprehension, to test each individual line:

[line for line in testdata if "This day is not yet available" in line]

or if you want the iterative version:

# result = []
for line in testdata:
    if "This day is not yet available" in line:
        # print(line) or result.append(line)

Try testing it out this way:

data = open('data.txt').readlines()
print(data)

print("\'This day is not yet available\'\n" in data)

At first I didn't include the newlines or the single quotes, but since I printed out the test data in the console after readlines() read it in, I got a clear view of what the 'in' statement would be acting on & was able to quickly correct the search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM