String.find () always evaluates to true
I have a small script that reads a file. After reading the line, I'm trying to figure out that the particular line has special text in it. For this I like this
for line in file:
line = line.lower()
if line.find('my string'):
print ('found my string in the file')
reading a file that line.find always evaluates to true. When i like
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 expected. Since I'm really new to python programming just for what I've shown, I just can't think of what I can find ...
source to share
find
returns the number containing the occurring string within the search string. If it doesn't find it, it returns -1
. And every number that is not 0
in python evaluates to True
. This is why your code is always evaluating 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))
source to share