gpt4 book ai didi

python-3.x - string.find() 的计算结果为 true

转载 作者:行者123 更新时间:2023-12-02 17:29:03 26 4
gpt4 key购买 nike

我有一个读取文件的小脚本。读完一行后,我试图找出该特定行中有特定的文本。因此我确实喜欢这个

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

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

读取 line.find 计算结果为 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-3.x - string.find() 的计算结果为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9932581/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com