Working with the str.replace() method in Python

Updated: June 1, 2023 By: Khue Post a comment

Syntax and Parameters

The str.replace() method in Python is used to replace occurrences of a specified substring within a string with another substring. It was added to the language from the early days and still is one of the most used string methods nowadays.

Syntax:

string.replace(old, new, count)

Where:

  • string: The original string on which the replacement operation is performed.
  • old: The substring to be replaced.
  • new: The substring that replaces the occurrences of the old substring.
  • count (optional): Specifies the maximum number of replacements to be made. If not provided, all occurrences of the old substring are replaced.

The replace() method searches for the old substring in the string and replaces it with the new substring. It returns a new string with the replacements applied, leaving the original string unchanged.

Examples

Some examples of using the str.replace() method in Python.

Basic Replacement

In this example, we will Replace a substring with another substring in a string:

text = "Hello, Sling Academy!"
new_text = text.replace("Hello", "Hi")
print(new_text) 

Output:

Hi, Sling Academy!

Multiple Limited Replacements

In this example, we will replace a substring with another substring in a string, but only a limited number of times.

text = "hello world, hello world, hello world, hello world, hello world"

# replace only the first three occurrences
new_text = text.replace("hello", "hi", 3)
print(new_text)

Output:

hi world, hi world, hi world, hello world, hello world

Multiple Replacements

This example demonstrates chaining replace() calls to perform multiple replacements:

text = "Welcome to Sling Academy!"

text = text.replace("!","").replace(" ", "_")
print(text)

Output:

Welcome_to_Sling_Academy

That’s it. Happy coding & have a nice day!