In this tutorial, we are going to learn about how to Replace a substring with a specific substring in Python in a simple and understandable way.
When we are creating code or something particularly long, we accidentally write the wrong word, which is repeated throughout the text. As a result, we will be dealing with an extremely stressful situation. To fix this difficulty, we can replace the substring with the substring that we want to replace. We use Python as a programming language because it has many useful features, such as object-oriented programming, ease of coding and reading, GUI programming support, and so on.
Replace a substring with a specific substring in python
Now, let us start with how to write a code in Python to replace a substring with a specific substring.
Firstly, we will create a variable called “string” which can hold the value or sentences given by us(the user).
string = "Hi!! I am Java. Java is a programming language and Java has many useful features like object-oriented programming and java is also a high level language." print("string = ",string)
Here, the string is a variable that holds the whole sentence, which is given above. This string describes a programming language called Java. But its actually written about a Python programming language. So, here we need to replace the word java with Python, and hence the problem will be solved!! Now, let’s consider the word “Java” as a substring since it is needs to be replaced.
substring = "Java"
Now, we will replace Java with Python so that it appears as Python in place of Java. Hence, we will create a replacing substring as “Python”.
replacing_substring = "Python"
To replace a substring with a specific substring in Python can be done using the string.replace() method. It searches through the string for all the occurrences of substring and it replaces them with replacing_substring and hence it is stored in the variable called replaced_substring.
replaced_substring = string.replace(substring,replacing_substring)
Finally, we will use the print() function, which provides the required output for us.
print("replaced_substring = ",replaced_substring)
At last, we will write the complete code all together at once for replacing a substring with a specific substring in Python.
string = "Hi! I am Java. Java is a programming language. Java has many useful features like object-oriented programming and Java is also a high level language." print("string = ",string) substring = "Java" replacing_substring = "Python" replaced_substring = string.replace(substring,replacing_substring) print("replaced_substring = ",replaced_substring)
The output for the above code is given below :
OUTPUT :
string = Hi! I am Java. Java is a programming language. Java has many useful features and Java is also a high level language. replaced_substring = Hi! I am Python. Python is a programming language. Python has many useful features like object-oriented programming and Python is also a high level language.