Replace Substring

Replace all occurrences of a substring with another substring.

PythonBeginner
Python
# Program to replace substring in a string

text = input("Enter main string: ")
old = input("Enter substring to replace: ")
new = input("Enter new substring: ")

result = text.replace(old, new)

print("Result:", result)

Output

Enter main string: hello world
Enter substring to replace: world
Enter new substring: Python
Result: hello Python

We use .replace(old, new) which returns a new string with all non-overlapping occurrences replaced.