1

Thank you for sharing the knowledge. I have a problem figuring out how to replace a value on a string.

for example

def replace(a, old, new):
  a.replace(old, new)
  return a 

replace('xy naxe is Exxa', 'x', 'm')

when I run this it returns the original without any replacements.

Mushif Ali Nawaz
  • 3,427
  • 3
  • 17
  • 28

3 Answers3

0

Just do :

x = "xy naxe is Exxa".replace('x','m')

Output

"my naxe is Exxa"
Sebastien D
  • 4,181
  • 4
  • 16
  • 43
0

Python strings are immutable. You can't make in-place replacements in Python.

a.replace(old, new) will return a new string, it won't update a.

So you need to return the result of this method. Because this method will have no impact on a.

Mushif Ali Nawaz
  • 3,427
  • 3
  • 17
  • 28
0

You can just execute .replace on them:

"xy naxe is Exxa".replace('x','m')

If x and m are variables:

"xy naxe is Exxa".replace(x,m)

It will return new string, not change original string because python strings are immutable.

Wasif
  • 13,656
  • 3
  • 11
  • 30