Python replace function


The Python replace() method replaces old with new in a string, or no more than max if the third parameter max is specified.

If you want to replace a substring, you can do so with the replace() method.

Related course: Complete Python Programming Course & Exercises

syntax

Syntax of the replace() method.

str.replace(old, new[, max])

parameters

  • old -- a substring that will be replaced.
  • new -- new string, used to replace the old substring.
  • max -- optional string, replace no more than max times

return value

Returns the new string generated after replacing old with new in the string, if the third parameter max is specified, then the replacement is not more than max times.

Python replace example

The following example shows the use of the replace() function.

#!/usr/bin/python

str = "this is string example... ...wow!!! ! this is really string"
print(str.replace("is", "was"))
print(str.replace("is", "was", 3))

The output of the above example is as follows.

thwas was string example... ...wow!!! thwas was really string
thwas was string example... ...wow!!! thwas is really string

example 2

The replace() function returns a new string, that's why it can be stored in a variable.

str1="abc abc abc abc"
str2=str1.replace("a", "A")
str3=str1.replace("a", "A",2)
print(str2)
print(str3)
input("Press Enter to end!")

This outputs:

Abc Abc Abc Abc
Abc Abc abc abc
Press Enter to end!

example 3

The example below filters keyboard input using the Python replace function. It removes the characters 'a','e','i','o','u' and 'y'.

n = input()
n = n.lower()
n = n.replace("a", "")
n = n.replace("e", "")
n = n.replace("i", "")
n = n.replace("o", "")
n = n.replace("u", "")
n = n.replace("y", "")
print(n)

example 4

Yet another example for completeness.

A simple word replace:

>>> a = "Hello world"
>>> b = a.replace("world","python")
>>> b
'Hello python'
>>>

Replace multiple words in a string:

>>> a = "Hello world world world world"
>>> b = a.replace("world","python")
>>> b
'Hello python python python python'
>>>

String replace is case sensitive, so "Hello" is not equal to "hello".

>>> a = "Hello hello Hello hello world"
>>> b = a.replace("hello","hi")
>>> b
'Hello hi Hello hi world'
>>>

You can call the replace method multiple times on a string:

>>> a = "Hello hello Hello hello world"
>>> b = a.replace("hello", "aloha")
>>> b = b.replace("Hello", "aloha")
>>> b
'aloha aloha aloha aloha world'