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.
# replace() with two parameters.string.replace(old_substring,new_substring)# replace() with three parameters.string.replace(old_substring,new_substring,no_of_times)
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. |
string = "Welcome to Educative!"# original stringprint(string)# with two Parametersprint(string.replace("Welcome","GoodBye"))
string_new = "Run Run Run people!"# original stringprint(string_new)# with three Parametersprint(string_new.replace("Run","Stop",2))
Free Resources