我有一个小脚本来读取文件.在读完一行后,我试图弄清楚特定的行中有特定的文本.因为我喜欢这样
for line in file:
line = line.lower()
if line.find('my string'):
print ('found my string in the file')
Run Code Online (Sandbox Code Playgroud)
读取line.find aways评估为true的文件.当我喜欢的时候
for line in file:
line = line.lower()
if 'one big line'.find('my string'):
print ('found my string in the file')
Run Code Online (Sandbox Code Playgroud)
正如它想象的那样,它评估为假.因为我对python编程很新,只是因为我已经展示了我只是想不出我可能会寻找什么...
find返回一个数字,它是搜索字符串中出现的字符串的位置.如果找不到,则返回-1.并且每个不在0python中的数字都会计算出来True.这就是你的代码总是评估的原因True.
你需要这样的东西:
if 'one big line'.find('my string') >= 0:
print ('found my string in the file')
Run Code Online (Sandbox Code Playgroud)
或更好:
idx = 'one big line'.find('my string')
if idx >= 0:
print ("found 'my string' in position %d" % (idx))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3751 次 |
| 最近记录: |