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,707
  • 3
  • 18
  • 31
  • 1
    Welcome to SO! This isn't valid Python--can you clarify? `replace` doesn't mutate the string object it's called on. Thanks. – ggorlen Oct 13 '20 at 16:01
  • 2
    `replace` returns new string. Strings in python are immutable. – 001 Oct 13 '20 at 16:01

3 Answers3

0

Just do :

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

Output

"my naxe is Exxa"
Sebastien D
  • 4,369
  • 4
  • 18
  • 46
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,707
  • 3
  • 18
  • 31
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
  • 14,755
  • 3
  • 14
  • 34