我需要从文件中读取数据。
f=open("essay.txt","r")
my_string=f.read()
以\nSubject:
开头并以\n
结尾的以下字符串位于my_string
Example:
"\nSubject: Good morning - How are you?\n"
如何搜索以\nSubject:
开头并以\n
结尾的字符串?
是否有任何python函数来搜索字符串的特定模式?
答案 0 :(得分: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()
答案 1 :(得分:2)
尝试startswith()。
str = "Subject: Good morning - How are you?\n"
if str.startswith("Subject"):
print "Starts with it."