Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.find() aways evaluates to true

Tags:

python

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.

like image 544
Bruno Araujo Avatar asked Oct 20 '25 09:10

Bruno Araujo


1 Answers

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))
like image 152
Pablo Santa Cruz Avatar answered Oct 21 '25 21:10

Pablo Santa Cruz



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!