Replace Substring in Python

Replace all occurrences of a substring with another substring.

BeginnerString ProgramsExample 9 of 25
replace-substring.py
Run in browser
1# Program to replace substring in a string
2
3text = input("Enter main string: ")
4old = input("Enter substring to replace: ")
5new = input("Enter new substring: ")
6
7result = text.replace(old, new)
8
9print("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.