Python String replace() Function
The String replace()
method returns a copy of the string in which all occurrences of a specified substring are replaced with another substring.
By default, all occurrences of the substring are replaced. However, you can limit the number of replacements by specifying optional parameter count
.
Syntax
my_string.replace(old, new, count)
replace() Parameters
Python String replace()
function parameters:
Parameter | Condition | Description |
---|---|---|
old | Required | A string you want to replace |
new | Required | A string you want to replace old string with |
count | Optional | An integer specifying number of replacements to perform. Default behaviour is replace all occurrences |
replace() Return Value
Python String replace()
function returns a copy of the string where the old
substring is replaced with the new
string. The original string remains unchanged.
If the old
substring is not found, it returns a copy of the original string.
Examples
Example 1: Replace Substrings in a String with replace()
The replace()
method replaces a substring within a string.
my_str = 'Tom is here!'
result = my_str.replace('Tom','David')
print(result) # Output: David is here!
output
David is here!
Example 2: Replace All Substrings in a String with replace()
By default, if you don't specify the count
parameter, the replace()
method replaces all occurrences of the specified substring.
my_str = 'Long, Longer, Longest'
result = my_str.replace('Long','Small')
print(result) # Output: Small, Smaller, Smallest
output
Small, Smaller, Smallest
Example 3: Replace a certain number of Substrings in a String with replace()
If you specify the optional parameter count
, then only the first count
occurrences are replaced.
my_str = 'Long, Longer, Longest'
result = my_str.replace('Long','Small', 2)
print(result) # Output: Small, Smaller, Longest
output
Small, Smaller, Longest