-1

I'm figuring out some basics in python, and somehow I don't get things to work.

string = 'water'

string.replace('a','u')

print(string)

I want this script to print out wuter. Yet even with the string.replace it still prints out water. What am I doing wrong?

Purag
  • 16,611
  • 4
  • 51
  • 72
Deltafox
  • 11
  • 1
  • 2
    Strings are ***immutable***. – PM 77-1 Aug 26 '20 at 21:27
  • 2
    replace() is an inbuilt function in Python programming language that returns a copy of the string – thibsc Aug 26 '20 at 21:27
  • Just to complement what previous comments said, I would recommend reading this old but helpful SO question which clarifies what does immutable means: https://stackoverflow.com/questions/9097994/arent-python-strings-immutable-then-why-does-a-b-work – KingDarBoja Aug 26 '20 at 21:31
  • Also type `help(string.replace)` and it tells you "Return a copy of S with all occurrences of substring old replaced by new." – alani Aug 26 '20 at 21:40

2 Answers2

2
string.replace('a','u')

doesn't change string. It returns a new string (which you discard in your case). Try

string = string.replace('a','u')

instead.

adjan
  • 12,776
  • 2
  • 29
  • 47
0

You can get it done using Regex module substitute

import re
my_string = 'water'
my_string2 = re.sub('a', 'u', my_string)
print(my_string2)
Seyi Daniel
  • 2,057
  • 2
  • 6
  • 17