-1

I want to replace only specific word in one string. However, some other words have that word inside but I don't want them to be changed.

For example, for the below string I only want to replace x with y in z string. how to do that?

x = "the"
y = "a"
z = "This is the thermometer"
Anisa Kollenhag
  • 103
  • 1
  • 8

2 Answers2

1
import re

pattern=r'\bthe\b' # \b - start and end of the  word
repl='a'
string = 'This is the thermometer'

string=re.sub(pattern, repl, string)
n1tr0xs
  • 408
  • 2
  • 9
  • thanks for the help. what if a word was like this. "this is 114-221 #114-221" and i only want to replace first 114-221 but not second one? – Anisa Kollenhag Feb 15 '20 at 10:26
0

In your case you can use re.sub(x, y, z). You can read the documentation here for more information.

Kurosh Ghanizadeh
  • 539
  • 1
  • 4
  • 16