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:
You can use string formatting here:
def replaceName(text, name):
newText = re.sub(r"\b{}\b".format(name), "visitor", text)
return str(newText)
Otherwise in your case re.sub
is just looking for the exact match "\bname\b"
.
text = "The sun is shining"
name = "sun"
replaceName(text,name)
# 'The visitor is shining'
Or for python versions of 3.6<
you can use f-strings as @wiktor has pointed out in the comments:
def replaceName(text, name):
newText = re.sub(rf"\b{name}\b", "visitor", text)
return str(newText)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With