How to Remove Substring from a String in Python

Last Updated on May 4, 2024 by Roshan Parihar

To remove a substring from a string in Python, 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 with examples given below.

How to Remove Substring from String Using replace() Function in Python?

If you want to replace or remove a substring from a string, use the replace() function that requires two arguments to pass in Python. The first argument is the substring to remove from the given string. The second argument is the string that you have to replace with the substring.

Example 1

Output

The 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.

Using translate() Function to Remove Single Specified Substring from String in Python

The translate() 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.

Example 2

Output

The 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. Use the same replace() as used in the first example above. However, it also requires passing the third argument as the number of characters to remove from the string.

Example 3

Output

The 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 increasing 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.