Python 3.x string.find()总是计算为true

Python 3.x string.find()总是计算为true,python-3.x,Python 3.x,我有一个读取文件的小脚本。在读了一行之后,我试图弄明白这一行中有一个特殊的文本。所以我很喜欢这个 for line in file: line = line.lower() if line.find('my string'): print ('found my string in the file') 读取line.find away计算为true的文件。当我喜欢的时候 for line in file: line = line.lower()

我有一个读取文件的小脚本。在读了一行之后,我试图弄明白这一行中有一个特殊的文本。所以我很喜欢这个

for line in file:
    line = line.lower()

    if line.find('my string'):
        print ('found my string in the file')
读取line.find away计算为true的文件。当我喜欢的时候

for line in file:
    line = line.lower()

    if 'one big line'.find('my string'):
        print ('found my string in the file')

它的计算结果为false,正如它假定的那样。由于我对python编程非常陌生,只是因为我已经展示了我想不出我可能会寻找什么…

find
返回一个数字,该数字是搜索字符串中出现的字符串的位置。如果找不到,则返回
-1
。python中不是
0
的每个数字的计算结果都是
True
。这就是为什么代码的计算结果总是
True

你需要像这样的东西:

if 'one big line'.find('my string') >= 0:
    print ('found my string in the file')
或者更好:

idx = 'one big line'.find('my string')
if idx >= 0:
    print ("found 'my string' in position %d" % (idx))

最好使用惯用python将其写成:

for line in file:
    line = line.lower()

    if 'my string' in line:
        print ('found my string in the file')
如果不关心字符串中的位置,则不要使用
.find()