2012-03-29 82 views
3

我有一個讀取文件的小腳本。讀完一行後,我試圖弄清楚特定行中有特定的文本。因此,我喜歡這樣做string.find()總是評估爲真

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

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

閱讀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') 

它評估爲假,因爲它假設要做。因爲我真的是新來的python編程只是爲了我所顯示的,我只是不能想到我可能會尋找什麼......

回答

1

這是更好的習慣蟒蛇爲寫:

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

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

,而不是使用.find(),如果你不不關心字符串中的位置。

+0

謝謝,這是我一直在尋找... – 2012-03-29 20:11:10

5

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)) 
相關問題