I have a function with which I'm using regular expressions to replace words in sentences.
The function that I have looks as follows:
def replaceName(text, name):
newText = re.sub(r"\bname\b", "visitor", text)
return str(newText)
To illustrate:
text = "The sun is shining"
name = "sun"
print(re.sub((r"\bsun\b", "visitor", "The sun is shining"))
>>> "The visitor is shining"
However:
replaceName(text,name)
>>> "The sun is shining"
I think this doesn't work because I'm using the name of a string (name in this case) rather than the string itself. Who knows what I can do so this function works?
I have considered:
- Using variable for re.sub, however although the name is similar, its a different question.
- Python use variable in re.sub, however this is just about date and time.