Reputation: 159
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 ?
Upvotes: 0
Views: 159
Reputation: 3835
Try startswith().
str = "Subject: Good morning - How are you?\n"
if str.startswith("Subject"):
print "Starts with it."
Upvotes: 2
Reputation: 133534
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()
Upvotes: 4