2014-12-03 155 views
0

有沒有辦法打印第一個字符串,只有當它發現字符串?例如:只打印Python文本文件中第一個找到的字符串

文本文件:

date.... 
author:... 
this is a list: 
there a string 1 here 
and there a string 2 there 
but also have string 3 here 
don't have string 4 there 

代碼:

for line in open(os.path.join(dirname, filename), "r").readlines(): 
    if line.find('string') != -1: 
     print "found ", line 

印刷:

found there a string 1 here 
+2

你能解釋更多的?它不清楚,第一個字符串? – Hackaholic 2014-12-03 10:10:54

回答

1

可以使用break停止循環。和in來檢查子字符串。

for line in open(os.path.join(dirname, filename), "r").readlines(): 
    if 'string' in line: 
     print("found "+line) 
     break 
0

替代方式使用with

with open(os.path.join(dirname, filename),'r') as f: 
    for line in f: 
     if 'string' in line: 
      print("found ", line) 
      break 
0

稍加修改你的代碼:

for line in open(os.path.join(dirname, filename), "r").readlines(): 
    if line.find('string') >=0: 
     print "found ", line 
     break      # to stop loop when string is found 

find字符串返回其他位置找到-1

相關問題