What is the string replace() method in Python?
The replace() method is a built-in functionality offered in Python programming. It replaces all the occurrences of the old substring with the new substring.
Replace() returns a new string in which old substring is replaced with the new substring.
Syntax
# replace() with two parameters.string.replace(old_substring,new_substring)# replace() with three parameters.string.replace(old_substring,new_substring,no_of_times)
Parameters
| Parameters | |
|---|---|
| old_substring | The substring you want to replace. |
| new_substring | The new substring with which you want to replace the old substring. |
| no_of_times (Optional) | The number of times you want to replace the old substring with the new substring. If this is not mentioned, all occurrences are replaced. |
Examples
1. With two Parameters
string = "Welcome to Educative!"# original stringprint(string)# with two Parametersprint(string.replace("Welcome","GoodBye"))
2. With three Parameters
string_new = "Run Run Run people!"# original stringprint(string_new)# with three Parametersprint(string_new.replace("Run","Stop",2))
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved