Reputation: 381
Okay, so I have this text file:
hello there hello print hello there print lolol
this is what I want to do in Python(down below in pseudo-code):
when print statement found:
print next five letters(not including space);
This is the result I want:
>>>[hello, lolol]
How do I solve this problem in python?
Upvotes: 0
Views: 299
Reputation: 106455
If there are always 5 letters that follow a print
and a space, you can use the following regex with lookbehind:
import re
print(re.findall(r'(?<=\bprint ).{5}', 'hello there hello print hello there print lolol'))
This outputs:
['hello', 'lolol']
Upvotes: 1
Reputation: 3801
split
by 'print '
and use list indexing to get the first 5 characters of the string
In [253]: [res[:5] for res in s.split('print ')[1:]]
Out[253]: ['hello', 'lolol']
Upvotes: 1