0

I need to read data from the file.

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

The below string which starts with \nSubject: and ends with \n is in the my_string

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

How can I search for the string which starts with \nSubject: and ends with \n ? Is there any python function to search for particular pattern of a string ?

4

2 回答 2

4

It's better to just search through the file line by line instead of loading it all into memory with .read(). Every line ends with \n, no line starts with it:

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

To search for it in that string:

import re
text = "\nSubject: Good morning - How are you?\n"
m = re.search(r'\nSubject:.+\n', text)
if m:
    line = m.group()
于 2013-04-22T06:31:12.763 回答
2

Try startswith().

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

if str.startswith("Subject"):
    print "Starts with it."
于 2013-04-22T06:42:35.940 回答