2013-04-22 152 views
0

我需要從文件中讀取數據。如何在另一個字符串中找到字符串的一部分?

f=open("essay.txt","r") 
my_string=f.read() 

\nSubject:開始,以\n結束的字符串下面是在my_string

Example: 
"\nSubject: Good morning - How are you?\n" 

我如何搜索與\nSubject:開始,以\n結束串? 是否有任何python函數來搜索字符串的特定模式?

回答

4

最好只是逐行搜索文件,而不是將它全部加載到內存中,並使用.read()。與\n每一行結束後,未行開始用它:

with open("essay.txt") as f: 
    for line in f: 
     if line.startswith('Subject:'): 
      pass 

要在該字符串進行搜索:

import re 
text = "\nSubject: Good morning - How are you?\n" 
m = re.search(r'\nSubject:.+\n', text) 
if m: 
    line = m.group() 
+0

我的問題是搜索一個字符串,以Subject開頭並以\ my_string結尾 – sunny 2013-04-22 06:34:15

2

嘗試startswith()。

str = "Subject: Good morning - How are you?\n" 

if str.startswith("Subject"): 
    print "Starts with it." 
相關問題