I have the following string
string = "House or r or place or r or floor or department or r"
I would like to replace stand-alone r
characters (meaning any letter r
that does NOT form part of a word) with another string, such as True
I have tried something like the following
string_replacement = string.replace("r", "True")
print(string_replacement)
Which outputs the following
House oTrue True oTrue place oTrue True oTrue flooTrue oTrue depaTruetment oTrue True
Instead, what I would like it to output is
House or True or place or True or floor or department or True
Thanks in advance
CodePudding user response:
You can use re.sub()
to replace standalone r
s. (The \b
in the regular expression refers to a word boundary.)
import re
string = "House or r or place or r or floor or department or r"
result = re.sub(r'\br\b', 'True', string)
print(result)
This outputs:
House or True or place or True or floor or department or True
CodePudding user response:
You can try with .replace(' r ', ' True ')