Replace Substring

Replace all occurrences of a substring with another substring.

BeginnerTopic: String Programs
Back

Python Replace Substring Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# 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

Understanding Replace Substring

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents