How do I replace a substring only if it is a whole word?
For example, if I want to replace the word "in" with "on" in the string "I was walking in Memphis.", and do this: result = re.sub("in", "on", string) # prints "I was walkong on Memphis." (Note "walkong".) I tried using regular expressions like r"\Win\W" to only replace the expression if it is surrounded by non-word characters. But this will also replace the surrounding whitespaces, for example: import re pattern = r"\Win\W" repl = "on" string = "I was walking in Memphis." result = re.sub(pattern, repl, string) print(result) # prints "I was walkingonMemphis." Any ideas? Update: Sharing my progress. The following code works, but only as long as there is only one occurrence of "in". Maybe I could fix that, but it feels like an unnecessarily complicated way to go: import re old_word = "in" pattern = r"\W" + old_word + r"\W" repl = "on" string = "I was walking in Memphis." match = re.search(pattern, string).group() splt = re.split(pattern, string) new_word = re.sub(old_word, repl, match) result = splt[0] + new_word + splt[1] print(result) # prints "I was walking on Memphis."