Replace Substring in Python
Replace all occurrences of a substring with another substring.
BeginnerString ProgramsExample 9 of 25
replace-substring.py
Run in browser1# Program to replace substring in a string23text = input("Enter main string: ")4old = input("Enter substring to replace: ")5new = input("Enter new substring: ")67result = text.replace(old, new)89print("Result:", result)
Output
Enter main string: hello world Enter substring to replace: world Enter new substring: Python Result: hello Python
What's going on
We use .replace(old, new) which returns a new string with all non-overlapping occurrences replaced.