English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python string replace() usage and example

Python string methods

The replace() method replaces the old string (old string) with the new string (new string) in the string. If the third parameter count is specified, it replaces no more than count times.

The syntax of replace() is:

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

replace() parameters

The replace() method can use at most3Parameters:

  • old -The old substring you want to replace

  • new -The new substring will replace the old substring

  • count(Optional)-The number of times you want to replace the old substring with the new substring

If count is not specified, the replace() method replaces all occurrences of the old substring with the new substring.

replace() return value

The replace() method returns a copy of the string where the old substring is replaced by the new substring. The original string remains unchanged.

If the old substring is not found, a copy of the original string is returned.

Example1How to use replace()?

song = 'cold, cold heart'
print(song.replace('cold', 'hurt'))
song = 'Let it be, let it be, let it be, let it be'
'''Only two occurrences of 'let' were replaced'''
print(song.replace('let', "don't let", 2))

When running the program, the output is:

hurt, hurt heart
Let it be, don't let it be, don't let it be, let it be

More examples of String replace()

song = 'cold, cold heart'
replaced_song = song.replace('o', 'e')
# The original string has not changed
print('The original string:', song)
print('The replaced string:', replaced_song)
song = 'let it be, let it be, let it be'
# Replace at most 0 substrings
# Return a copy of the original string
print(song.replace('let', 'so', 0))

When running the program, the output is:

The original string: cold, cold heart
The replaced string: celd, celd heart
let it be, let it be, let it be

Python string methods