Replace Substring in Python

Replace all occurrences of a substring with another substring.

BeginnerString ProgramsExample 9 of 25
replace-substring.py
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.

After this program

If the idea is still fuzzy, read Day 4: Strings and String Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 string programs, or see every topic on Python exercises.