Sling Academy
Home/Python/Python: 4 Ways to Remove Substrings from a String

Python: 4 Ways to Remove Substrings from a String

Last updated: May 31, 2023

This concise, example-based article will walk you through several approaches to removing one or many substrings from a given string in Python. No time to waste; let’s get our hands dirty with code.

Using the replace() method

This approach is quick and straightforward. Here’s what you need to do to get the job done:

  1. Call the replace() method on the string and pass the target substring and an empty string as arguments.
  2. Repeat the process for each substring you want to remove.
  3. Assign the modified string back to the original variable or a new variable.

Example (remove a substring):

text = "'Hello World!' is a boring sample string."

# Remove "boring" from text
text = text.replace("boring ", "")
print(text)

Output:

'Hello World!' is a sample string.

Another example (remove a list of substrings):

# define a reusable function
def remove_substrings_replace(text, substrings):
    for substring in substrings:
        text = text.replace(substring, '')
    return text

# a list of substrings to remove
substrings = ["blue", "red", "green"]

text = "blue Welcome red to green Sling sample blue red Academy!"
result = remove_substrings_replace(text, substrings)
print(result)

Output:

 Welcome  to  Sling sample   Academy!

Using regular expressions

You can use regular expressions to find and remove the target substrings using the re.sub() function. This approach is a little tough for beginners, but it provides more flexibility, such as can eliminate substrings regardless of case sensitivity.

Example (basic):

import re

def remove_substrings_regex(text, substrings):
    pattern = '|'.join(map(re.escape, substrings))
    return re.sub(pattern, '', text)

text = """one two three four 
one two three four
five six two three four
eleven two three five
"""
substrings = ["two", "three"]
result = remove_substrings_regex(text, substrings)
print(result)

Output:

one   four 
one   four
five six   four
eleven   five

To remove substrings ignoring case sensitivity, you need to use the re.IGNORECASE flag when creating a pattern object or calling a function from the re module.

Example:

import re

string = "slingacademy.comFOOFOObarBARbar"

# substrings to remove
substring1 = "foo"
substring2 = "bar"
pattern = re.compile(f"({substring1}|{substring2})", re.IGNORECASE)

# Remove all occurences of substrings regardless of case
new_string = pattern.sub("", string)
print(new_string)

Output:

slingacademy.com

Using the partition() method

You can use the partition() method to split the string into three parts: the part before the substring, the substring itself, and the part after the substring. Then you can use the join() method to join the parts without the substring.

Example:

string = "You are the Wolf of Wall Street, aren't you?"
substring = " of Wall Street"
before, match, after = string.partition(substring)
new_string = before + after
print(new_string)

Output:

You are the Wolf, aren't you?

Using the removeprefix() and removesuffix() methods

The removeprefix() and removesuffix() methods have been available since Python 3.9, and you can make use of one of them to remove a prefix or suffix from a given string, respectively.

text = "Hello World! Welcome to Sling Academy. Goodbye World!"

# remove "Hello World! "
text = text.removeprefix("Hello World! ")

# remove "Goodbye World!"
text = text.removesuffix(" Goodbye World!")

print(text)

Output:

Welcome to Sling Academy.

Next Article: Python: Remove non-alphanumeric characters from a string

Previous Article: Working with Raw Strings in Python

Series: Working with Strings in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots