How to Remove Substring from String Using Python

Last Updated on July 14, 2021 by Roshan Parihar

In this tutorial, learn how to remove substring from string in Python. The short answer is to use the replace() function that deletes required characters from a string.

You can also delete a single specified substring from a string using the translate() function in Python. Let’s find out and learn the different methods with examples given below here.

Method 1: Using replace() to Remove Substring from String in Python

To replace or remove substring from string, you can use the replace() function of Python that takes two arguments. The first argument is the substring that you want to remove from the given string in Python. The second argument is the string that you have to replace with the substring. See the method given below to learn the use of the function.

Output

Initial string is: Welcome todeep TutorialDeep! deep deep
New String is: Welcome to TutorialDeep!

The above example contains the substring ‘deep’ for three times that you have to remove using the replace() in Python. The function removes or replaces all the substrings from the given string.

Method 2: Using translate() to Remove Single Specified Substring from String in Python

If you want to remove a single specified substring from the string, you can use the translate() function. The function takes a single argument as the ord() within the curly brackets. Inside that function, you need to specify the single character that you have to remove from the string using Python.

Output

Initial string is: Welcome deep TutorialDeep!
New String is: Welcome deep TutorialDeep

The above example shows the initial string and the new string. The function removes the single substring ‘!’ from the string in Python.

Delete Specified Number of Characters From String in Python

In addition to the above methods, you can also delete the specified number of characters from the given string in Python. To perform this task, you have to use the same replace() that you have used in the first example above. However, it also requires passing the third argument to the function that is the number of characters that you have to remove from the string.

Output

Initial string is: Welcome todeep TutorialDeep! deep deep
New String is: Welcome to TutorialDeep! deep deep

The above example contains the replace() with the third argument is 1. This shows that it removes a single specified substring from the string. Similarly, you can remove more substrings by increase the value of the third argument using Python.

The last method is when you have to remove the limited number of substrings from the given string in Python.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.