我需要从文件中读取数据。
f=open("essay.txt","r")
my_string=f.read()以下字符串位于my_string中,该字符串以\nSubject:开头,以\n结尾
Example:
"\nSubject: Good morning - How are you?\n"如何搜索以\nSubject:开头、以\n结尾的字符串?有没有什么python函数可以搜索字符串的特定模式?
发布于 2013-04-22 14:31:13
最好是逐行搜索文件,而不是使用.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()发布于 2013-04-22 14:42:36
尝试startswith()。
str = "Subject: Good morning - How are you?\n"
if str.startswith("Subject"):
print "Starts with it."https://stackoverflow.com/questions/16140724
复制相似问题