. Advertisement .
..3..
. Advertisement .
..4..
In this tutorial, we will learn ”Tips On Removing Substring From String in Python”. Python has a rich collection of modules. Here we will use modules to remove substrings from a given string in Python.
How Can You Remove Substring From String in Python?
Option 1: Utilize str.replace()
You can remove substring from string in Python by utilizing str.replace().
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 use this method to substitute the string:
Input:
vab1 = "have a good day" x = vab1.replace("o", "k", 2) print(x)
Output:
have a gkkd day
Option 2: Utilize loop + replace()
You also can use replace() with a loop to delete multiple strings in this approach. It will be easier to comprehend if you consider the following example:
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
As a result, you can use loop and replace() to delete substrings.
Option 3: Utilize the translate() function
With the help of the translate() function in Python, you will be able to remove a substring from a string. Another Python function, translate(), uses the specified translation table to substitute a character or a substring from a string. The translate() function accepts a Unicode representation of a character that has to be changed in a string along with a replacement identifier of “None” to get rid of the character entirely. The Unicode of a character that is sent to the translation table is obtained using the ord() Python method. The syntax of the translate() function is as follows:
translate({unicode: None})
Run the following code to operate the translate():
_String = “This is a test string.”
New_Str = _String.translate({ord(“i”): None})
print(New_Str)
Output:
This is a test string
>>>
Conclusion
We hope you will enjoy our blog about ”Tips On Removing Substring From String in Python”. If you have any other questions or concerns about this issue, please leave a comment below. Thank you for reading; we are always excited when one of our posts can provide useful information on a topic like this!
Read more
Leave a comment