In this tutorial We will Discuss about How to remove substring From String in Python. Its about that string not remove but just replaced. Here are some different methods to remove substring from string.
How to Remove Substring From String in Python
How to Remove Substring From String in Python
To Remove Substring From String in Python use str.replace() In this method you can replace the string via using the str.replace(). It will replace the substring as a below example:
Input :list1 = {'burger.1','pizza.2','vadapav.1','bhajiya.2'} vab1 = {x.replace('.1','').replace('.2','')for x in list1} print(vab1)
Output :{'pizza', 'vadapav', 'burger', 'bhajiya'}
You can also replace the string by this way:Input :vab1 = "have a good day" x = vab1.replace("o", "k", 2) print(x)
Output :have a gkkd day
Remove Substring From String in
To Remove Substring From String in Python use loop + replace() In this method we will remove multiple strings by using replace() with loop. it will be better to understand by this example which is given below: Input :
var1 = "best of luck for your exam" print("The original string is : " + var1) list = ["of", "your"] for sub in list: var1 = var1.replace(' ' + sub + ' ', ' ') print("The string after substring removal : " + var1)
Output :The original string is : best of luck for your exam The string after substring removal : best luck for exam
Thus we can remove substring by using loop and replace(). I hope you like it.
Method 1 : use str.replace()
In this method you can replace the string via using the str.replace(). It will replace the substring as a below example of remove substring from string python
list1 = {'burger.1','pizza.2','vadapav.1','bhajiya.2'}
vab1 = {x.replace('.1','').replace('.2','')for x in list1}
print(vab1)
Output :
{'pizza', 'vadapav', 'burger', 'bhajiya'}
You can also replace the string by this way:
vab1 = "have a good day"
x = vab1.replace("o", "k", 2)
print(x)
Output :
have a gkkd day
Method 2 : use loop + replace()
In this method we will remove multiple strings by using replace() with loop. it will be better to understand by this example which is given below:
var1 = "best of luck for your exam"
print("The original string is : " + var1)
list = ["of", "your"]
for sub in list:
var1 = var1.replace(' ' + sub + ' ', ' ')
print("The string after substring removal : " + var1)
Output :
The original string is : best of luck for your exam
The string after substring removal : best luck for exam
Thus we can remove substring by using loop and replace(). I hope you like it.
Conclusion
It’s all About this Tutorial. Hope all methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you?
Also, Read