In this Python tutorial, We will see how to remove substring from string in Python if exist using different methods with examples.
Strings are one of the essential data types in Python. As developers, We often need to manipulate strings for various purposes, such as cleaning data, extracting information, or simply making the data more readable. One such common operation is the removal of a specific substring from a Python string.
A substring is a portion or segment of a Python string that is extracted from the main Python string.
Let’s see how to create a string in Python and what are the substring of this Python string.
USA = 'United States of America'
print(type(USA))
The output is:
<class 'str'>
In the above example as we can the USA is from a str class in Python. Here, we have many substrings such as ‘United’, ‘States’, ‘of’, ‘America’, etc.
Let’s explore different ways to remove substring from string python.
Remove substring from string in Python if exist
There are many different ways to remove substring from string in Python:
- the replace() Method
- Using split() and join()
- Using List Comprehensions
- Using String Slicing
- Using Regular Expressions (regex)
- Using the lstrip() and rstrip() methods
Let’s see them one by one with examples:
Method 1: Remove substring from string python with replace() method
To remove a substring from a Python string, we use the replace() method, a built-in Python function that allows us to replace a specific part of a string with another. If we want to remove a substring, we replace it with an empty string “”.
Imagine we’re working with a list of state names, and we need to remove the suffix “State” from any state name that has it. Let’s use “The Golden State,” a nickname for California, as an example.
state = "The Golden State"
state_without_suffix = state.replace(" State", "")
print(state_without_suffix)
This will output:
The Golden
This way we can Remove substring from string in Python if exist with replace.
Method 2: Python remove substring from string with split() and join()
The split() function breaks up a Python string into a list of words, using the substring as a delimiter. If we combine this with the join() function, we can effectively remove the substring from the string Python. However, this will remove all instances of the substring, and it doesn’t work well with substrings at the beginning or end of the string.
For instance, let’s remove the word ‘Liberty’ from the famous quote “Give me Liberty or give me death” in Python:
quote = "Give me Liberty or give me death"
new_quote = " ".join(quote.split('Liberty'))
print(new_quote)
This will output:
Give me or give me death
This way we can Remove substring from string in Python if exist with split() and join().
Method 3: Remove a substring from a string in Python with List comprehension
Python’s list comprehension provides a concise way to create lists. It consists of brackets containing an expression followed by a for statement, and optionally for or if clauses. It can be used to remove a substring as follows:
Suppose we have a variable in Python that stores some state’s name from the US, separated by commas. And we want one of the state’s names from it. We need to remove substring from string in Python if exist. Let’s check how to do this with list comprehension in Python:
states = "Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut"
remove_state = "Alaska"
states = ", ".join([state for state in states.split(", ") if state != remove_state])
print(states)
The output is:
Alabama, Arizona, Arkansas, California, Colorado, Connecticut
This way we can use List comprehension to Python string remove substring.
Method 4: Python remove pattern from string using string slicing
Python allows us to slice strings, which can be very useful if we know the exact position (index) of the substring we want to remove:
For instance, we have a string “Washington D.C., the capital of the USA”, and we want to remove the substring “the capital of the USA”. Here is how we do it:
str = "Washington D.C., the capital of the USA"
index = str.find("the capital of the USA")
if index != -1:
str = str[:index]
print(str)
Here, Python provides a find() method to find the position of a substring in a string. It returns the index of the first occurrence of the substring. If the substring is not found, it returns -1.
The output is:
Washington D.C.,
Note: We can use negative indices also to Remove substring from string in Python if exist.
This way we can use list slicing with the find function to Python remove pattern from string.
Method 5: Remove substring from string python regex
Regular expressions(regex) can handle very complex patterns and can be a powerful tool for string manipulation. For example, we will import the re module and the sub() function can be used to replace substrings.
Suppose we have a statement as a Python string and want to remove a word from it, Then we can:
import re
string = "The capital of California is Sacramento, and the capital of New York is Albany."
string = re.sub('Sacramento', '', string)
print(string)
The output is:
The capital of California is , and the capital of New York is Albany.
This way we can remove substring from string Python regex.
Method 6: Python remove substring if exists using lstrip and rstrip
Python’s lstrip() and rstrip() methods can be used to remove characters from the left or right side of a string. If the substring is located at the beginning or end of the string.
For instance, we have two words StateWashington and WashingtonState and we want only Washington in both cases, we will use lstrip and rstrip one by one to remove State from each respectively:
state = "StateWashington"
new_state = state.lstrip('State')
print(new_state)
The output is:
Washington
This way we can use lstrip to remove substring in Python if exists.
state = "WashingtonState"
new_state = state.rstrip('State')
print(new_state)
The Output is:
Washington
This way we can use rstrip to remove substring in Python if exists.
Note: lstrip() and rstrip() remove all occurrences of each character in the given string from the left or right side. So if the substring we’re removing has any characters that also appear in the main string after (for lstrip()) or before (for rstrip()) the substring, those characters will be removed as well.
Conclusion
In this article, we have seen how to remove substring from string in Python if exist with different methods like replace(), split(), and join(), list comprehension, string slicing, regex, lstrip(), and rstrip() using demonstrative examples
You may like the following Python tutorials:
- Slicing string in Python + Examples
- Convert string to float in Python
- Append to a string Python + Examples
- Strip function in Python string
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.