Python string replace() method

Python String replace() Method

Description

The replace() method returns a copy of a string with the old string replaced by the new string, optionally limiting the number of replacements.

Syntax

The syntax of the replace() method is as follows:

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

Parameters

  • old − The old substring to be replaced.
  • new − The new substring to replace the old substring.
  • max − If the optional max parameter is given, only the first max occurrences of the substring are replaced.

Return Value

This method returns a copy of a string with all occurrences of the old substring replaced by the new substring. If the optional argument max is given, only the first max occurrences of the substring are replaced.

Example

The following example demonstrates the use of the replace() method.

var = "Explicit is better than implicit."
var1 = var.replace('Excellent', 'Good')
print("Original string:", var)
print("Replaced string:", var1)

When you run this program, the following output is produced −

Original string: Explicit is better than implicit.
Replaced string: Explicit is better than implicit.

Leave a Reply

Your email address will not be published. Required fields are marked *