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 ?

2 Answers 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()
Sign up to request clarification or add additional context in comments.

1 Comment

My questions is to search for a string which starts with Subject and ends with \n in my_string
2

Try startswith().

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.