Adding characters after a certain word in Python using regex

Use re.sub() to provide replacements, using a backreference to re-use matched text:

import re

text = re.sub(r'(get)', r'\1@', text)

The (..) parenthesis mark a group, which \1 refers to when specifying a replacement. So get is replaced by get@.

Demo:

>>> import re
>>> text="Do you get it yet?"
>>> re.sub(r'(get)', r'\1@', text)
'Do you get@ it yet?'

The pattern will match get anywhere in the string; if you need to limit it to whole words, add \b anchors:

text = re.sub(r'(\bget\b)', r'\1@', text)

Leave a Comment