Scott Scott - 4 months ago 27
Python Question

Python Get first word after substring in string

Hi I'm trying to get the word after a specified sub string, like...

str = Quote from: Bob1 ...


I'm trying to search for everytime Quote from: appears and get the word after, in this case Bob1.

I've tried:

print((re.findall(r'Quote from:\a\X\\9', str)))


But it just returns []

Answer

This should work for you, using split.

>>> str = "Quote from: Bob1 ..."
>>> str.split("Quote from:")[1].split()[0]
'Bob1'

Why you should avoid regex read this.