I have a small script that reads a file. After reading a line I'm trying to figure out if the particular line has a specific text in it. I do so like this:
for line in file:
line = line.lower()
if line.find('my string'):
print ('found my string in the file')
I find that line.find always evaluates to true. When I do this
for line in file:
line = line.lower()
if 'one big line'.find('my string'):
print ('found my string in the file')
it evaluates to false, as it's supposed to do.
find returns a number that's the position of the occurring string inside the search string. If it does not find it, it return -1. And every number that's not 0 in python evaluates to True. That's why your code always evaluates to True.
You need something like:
if 'one big line'.find('my string') >= 0:
print ('found my string in the file')
Or, better:
idx = 'one big line'.find('my string')
if idx >= 0:
print ("found 'my string' in position %d" % (idx))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With