22
votes

I have a text file and every time that the word "get" occurs I need to insert an @ sign after it.

In Python how do I add a character after a specific word using regex? Right now I am parsing the line word by word and I don't understand regex enough to write the code.

1
do you want to add an @ after midget ? - Casimir et Hippolyte
I do not want to add after midget. Does that change the regex? - English Grad
Yes, a little. Martijn Pieters has the good answer. You only need to add word boundaries before and after the word "get" in the pattern: \bget\b - Casimir et Hippolyte

1 Answers

40
votes

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)