How to Remove a Substring from a String in Python

Recently, while cleaning up some text data for a project, I ran into a common issue: I had to remove a specific substring from strings, but only if that substring existed.

At first, I thought there might be a built-in function for this, but Python doesn’t have a single “remove substring if exists” method. Instead, we can use a few simple techniques to get the job done.

In this tutorial, I’ll walk you through different methods I’ve used over the years to remove substrings from strings in Python. These methods are beginner-friendly, but they’re also efficient enough to use in real-world applications.

Methods to Remove a Substring from a String in Python

Let’s understand the scenario clearly so you can use the method in the correct situation.

So there is text like this,

text = "Welcome to Python Guides...you can learn Python from basic to advance"\
remove = "...you can learn Python from basic to advance"

Now I need to remove some phrases from the text and need this as an output.

Welcome to Python Guides

In this scenario, you can use all the approaches we will explain.

1: Use Python’s replace() Method

Here, I will replace the given substring pattern with an empty string. This method does not affect the original string.

Syntax

var_name.replace(old_string_pattern, new_string)
  • In the above syntax, the “var_name” should be a string datatype only.
text = "British colonization led to the first settlement of the Thirteen Colonies"
updated_string = text.replace("of the Thirteen Colonies", "")
print(updated_string)

You can refer to the screenshot below to see the output.

Python remove substring from string if exists using replace() method

I need to remove the word “State” from the string, so I replaced “State” with “Empty string” like this: ‘state.replace(” State”, ” “)’ using a method to remove the substring in Python and store it in the updated_string variable.

2: Use split() and join() Method in Python

I will use the join() and Python split() methods to remove the substring from the string. The join() method is used to concatenate strings in Python.

The split() method separates all the words based on the given separator value and creates a list of all the words in the string.

Syntax of join() method

string.join(["str1" , "str2", ... ])

Syntax of split() method

string.split("seperator")
  • string.split(“separator”): split() method will be used for string datatype only. If you don’t give value to the separator, it will take white space as a default value
text = "The United States has had the largest nominal GDP in the world"

updated_text = " ".join(text.split('has had the largest nominal GDP in the world'))
print(updated_text)

You can refer to the screenshot below to see the output.

Remove substring from string Python using split() and join()

I have used the split() method to separate the needed string part, so it will look like this
“[‘The United States ‘, ”]” and then it will concat to updated_text using join() method.

3: Use List Comprehensions in Python

I will take the same approach as in the previous example, but this time, I will separate the string into a list based on the commas. Then, I will use list comprehension to iterate over every list element.

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)

You can refer to the screenshot below to see the output.

How to remove substring from string in Python using List Comprehensions

In the above code, we use a for loop after splitting the string values, and then we put the condition “if state != remove_state” to include the elements that do not match the remove_state value.

4: Use Python Regular Expressions (regex)

I can also use Regular expressions, also known as regex, in Python, to remove substrings of a string using the re.sub() method in Python.

Syntax

re.sub(pattern, replce pattern, input_string)
  • Before using the re.sub() method, you have to import the re module.
  • re.sub(pattern, replace pattern, input_string): In the pattern, you will give the targeted perhaps that you want to replace, and in replace_pattern, you can give another string you wish to include.
  • Input_string will be the main string from where you want to make changes.
import re

string = "The capital of California is Sacramento, and the capital of New York is Albany."
string = re.sub(', and the capital of New York is Albany', '', string)
print(string)

You can refer to the screenshot below to see the output.

Python remove substring if exists using Regular Expressions (regex)

So I gave an empty string in the replace string parameter “re.sub(‘, and the capital of New York is Albany’, ”, string)” so it will remove the pattern you’ve given in the first parameter.

5: Use Python String Slicing

It is a process of extracting the elements by giving the range of the index position. Also, we will use the find() method in Python to get the index value of the given string.

Syntax of String Slicing in Python

string[start_index : end_index]
  • string[start_index: end_index]: If you don’t provide anything at index positions, it will select the whole string by default.
  • Index positions should always be integer values; otherwise, it will give an error.
str = "Washington D.C., the capital of the USA"

index = str.find(", the capital of the USA")
str = str[:index]
print(str)

You can refer to the screenshot below to see the output.

Python remove substring from string using String Slicing

In the above code, we’ve initialized a variable named index and assigned the index position of the element using the find() method, which we need to remove from the string.

6: Use Python’s lstrip() and rstrip() Methods

I can also use the lstrip() and rstrip() methods to remove the substring, but the condition is that the removable string should be at the start index or the last index.

1. Use lstrip() Method

The lstrip () method removes the elements to the left of the string at the start index position.

Syntax

string.lstrip('value_to_be_remove')
  • string.lstrip(‘value_to_be_remove’): If you don’t give any value in the parameter, then it will remove the white space at the start index if it is there.
state = "state name is Washington, also known as evergreen state"
new_state = state.lstrip('state')
print(new_state)

You can refer to the screenshot below to see the output.

Remove a substring from a string in Python using the lstrip() method

The above code has a string that includes the state word at the start and end. So, if you need to remove the first word only on the left side, you can use the lstrip() method, like this: “state.lstrip(‘state’)”

2. Use rstrip() Method

The rstrip () method removes the elements to the right of the string at the end index position.

state = "The state name is Washington, also known as evergreen state"
new_state = state.rstrip('state')
print(new_state)

You can refer to the screenshot below to see the output.

Python Remove Substring From String If Exists using rstrip() method

In the above, we took the same example as the previous one, but here we are removing the pattern “new_state = state.rstrip(‘state’)”, which is at the last index position.

In this Python article, you learned how to remove a substring from a string in Python. We explored 6 different methods and techniques, including the replace() method, list comprehension, regex, and more, with practical examples for every method.

You can read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.