如何在另一个字符串中找到字符串的一部分?

2024-04-25 21:28:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从文件中读取数据。你知道吗

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

以下字符串以\nSubject:开始,以\n结束,位于my_string

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

如何搜索以\nSubject:开始并以\n结束的字符串? 有没有python函数来搜索字符串的特定模式?你知道吗


Tags: 字符串txtyoureadstringexamplemyopen
2条回答

最好是逐行搜索文件,而不是用.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()

尝试startswith()。你知道吗

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

if str.startswith("Subject"):
    print "Starts with it."

相关问题 更多 >