Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a variable name in re.sub [duplicate]

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:

  1. Using variable for re.sub, however although the name is similar, its a different question.
  2. Python use variable in re.sub, however this is just about date and time.
like image 679
Emil Avatar asked Jan 26 '23 04:01

Emil


1 Answers

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)
like image 132
yatu Avatar answered Jan 29 '23 12:01

yatu