Python replace() Method

Python 字符串Python Strings


Description

The Python replace() method replaces old (old string) in the string with new (new string). If the third parameter max is specified, the replacement is performed no more than max times.

Syntax

Syntax of the replace() method:

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

Parameters

  • old -- The substring to be replaced.
  • new -- The new string, used to replace the old substring.
  • max -- Optional string; replaces no more than max times.

Return Value

Returns the new string generated by replacing old (old string) in the string with new (new string). If the third parameter max is specified, the replacement is performed no more than max times.

Example

The following example demonstrates how to use the replace() function:

Example

#!/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:

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

Python 字符串Python Strings

Other Extensions