2024-04-25 21:28:45 发布
网友
我需要从文件中读取数据。你知道吗
f=open("essay.txt","r") my_string=f.read()
以下字符串以\nSubject:开始,以\n结束,位于my_string
\nSubject:
\n
my_string
Example: "\nSubject: Good morning - How are you?\n"
如何搜索以\nSubject:开始并以\n结束的字符串? 有没有python函数来搜索字符串的特定模式?你知道吗
最好是逐行搜索文件,而不是用.read()将其全部加载到内存中。每行以\n结尾,没有一行以它开头:
.read()
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()
尝试startswith()。你知道吗
str = "Subject: Good morning - How are you?\n" if str.startswith("Subject"): print "Starts with it."
最好是逐行搜索文件,而不是用
.read()
将其全部加载到内存中。每行以\n
结尾,没有一行以它开头:要在该字符串中搜索它:
尝试startswith()。你知道吗
相关问题 更多 >
编程相关推荐