I have a text file and every time that the word "get" occurs, I need to insert an @ sign after it.
How do I add a character after a specific word 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)
get in a variable? I mean how to set pass_variable_dynamically = "get" #may be some other string re.sub(r'pass_variable_dynamically', r'\1@', text)) not workingre.escape() and use normal string interpolation techniques: re.sub(r'(\b{}\b)'.format(variable), r'\1@', text) would use variable to obtain the word to replace.re.sub(rf'(\b{variable}\b), r'\1@', text)You can replace (zero-width) matches of (?<=\bget\b) with '@'.
import re
text = re.sub(r'(?<=\bget\b)', '@', text)
(?<=\bget\b) is a positive lookbehind. It asserts that the (zero-width) match is immediately preceded by 'get'. The word boundaries \b are added to prevent matching that string when it is immediately preceded and/or followed by a word character (such as 'budget', 'getting' or 'nuggets').
To insert a character after every occurrence of a string ('get'), you don’t even need regex. Split on 'get' and concatenate with '@get' in between strings.
text = 'Do you get it yet?'
'get@'.join(text.split('get')) # 'Do you get@ it yet?'
However, if 'get' has to be an entire word, re.split() could be used instead.
text = 'Did you get it or forget?'
'get@'.join(re.split(r"\bget\b", text)) # 'Did you get@ it or forget?'
re.split results is any simpler than using re.sub.str.split was simpler. I agree, re.split is not simpler.
@aftermidget?\bget\b