python string replace in python 3.x

Python String replace() Method

There are two ways for replacing a String for python 2.x and also 3.x, use str.replace().

The replace() method in python 3 is used simply.

Example for a string replace:

>>> 'Hello world'.replace('world', 'Welt')
'Hello Welt'

or calling the method replace() of  <class 'str'> in python 3.x:

>>> 'hello, world'.replace(',', ':')
'hello: world'

Notes from Python Docs:

  • Method 1: use builtin str’s replace -> str.replace(strVariable, old, new[, count])
replacedStr1 = str.replace(originStr, "from", "to")
  • Method 2: use str variable’s replace -> strVariable.replace(old, new[, count])
replacedStr2 = originStr.replace("from", "to")

Leave a comment