What is the grep equivalent in Python?

You could use the in keyword to check for your substring:

with open('text_file.txt', 'r') as f:
    for line in f.readlines():
        if 'elephant' in line:
            print(line)

Or, if you had a string s with \n characters:

for line in s.split('\n'):
    if 'elephant' in line:
        print(line)

Your regex only prints elephant because that’s what it captured: exactly your regex string. If you were to try the following regex instead:

test = re.search(r'(.*?elephants.*?)\n', 'I like elephants.\nThey are nice')

Then you’d have results for test.group(0) and test.group(1) which include the whole line before and after the elephants.

In [22]: test.group(0)
Out[22]: 'I like elephants.\n'

That’s the whole captured string.

In [23]: test.group(1)
Out[23]: 'I like elephants.'

That’s just the capture group (string between parentheses).

Leave a Comment