0

I am just learning python and wanted to create a little program which changes words in a string. But for some reason it doesn't work how i intended.

here is the code i try to run.

#setting text as variable
text= "hi my name is john"

#replacing the names
text.replace ("john", "peter")

#printing the new string
print (text)

for my understanding of the function replace () shouldn't it replace john with peter? or what is my mistake?

thanks in advance

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
dezanos
  • 11
  • 1
  • 5

2 Answers2

0

the replace function returns a new string object and is not assigned to the text variable. use:

#setting text as variable
text= "hi my name is john"

#replacing the names 
text = text.replace ("john", "peter")

#printing the new string
print (text)
Itay Dumay
  • 139
  • 10
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer), see the section *Answer Well-Asked Questions*, and therein the bullet point regarding questions that "have been asked and answered many times before". – Charles Duffy Dec 08 '20 at 22:16
-1

String is immutable,so you must create new string variable

text_2=text.replace("john","peter")
Print(text_2)