Python has builtin support for string replacement. A string is a variable that contains text data. If you don’t know about strings, you can read more about strings in this article.

Can call the string.replace(old, new) method using the string object. This article demonstrates the replace method.

Not all programming languages have a standard string replace function. Python has a lot of functionality that comes out of the box.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

Example

Replace method

Define a string and call the replace() method. The first parameter is the word to search, the second parameter specifies the new value.

The output needs to be saved in the string. If you don’t save the output, the string variable will contain the same contents. Saving output is done using: s = function()

Try the program below:

s = "Hello World"
s = s.replace("World","Universe")
print(s)

Save the program as app.py, then run in terminal (or IDE)

python app.py

This will output the new output of string variable s:

python replace

Number of words to replace

An optional parameter is the number of items that will be replaced. By default its all.
The program below replaces only the first item:

s = "Hello World World World"
s = s.replace("World","Universe",1)
print(s)

The parameter (1) indicates that the string should be replaced only once.

Exercise

Exercises below

  1. Try the replace program
  2. Can a string be replaced twice?
  3. Does replace only work with words or also phrases?

Download answers