Python String replace() method is used to replace occurrences of the specified substring with the new substring.
Syntax of replace() method
Syntax of replace() method is-
str.replace(old, new, count)
old- Specifies a substring that has to be replaced.
new- Specifies a substring that replaces the old substring.
count- count argument is optional if it is given, only the first count occurrences are replaced. If count is not specified then all the occurrences are replaced.
Return values of the method is a copy of the string with all occurrences of substring old replaced by new.
Replace() method Python examples
1. Replacing specified substring with new value.
def replace_sub(text): text = text.replace('30', 'thirty') print(text) replace_sub('His age is 30')
Output
His age is thirty
2. replace() method with count parameter to replace only specified occurrences.
def replace_sub(text): text = text.replace('is', 'was') print(text) # replacing only one occurrence print(text.replace('was', 'is', 1)) replace_sub('His age is 30')
Output
Hwas age was 30 His age was 30
3. Replacing character with space.
def replace_sub(text): text = text.replace('H', '') print(text) replace_sub('His age is 30')
Output
is age is 30
That's all for this topic Python String replace() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-