How to Remove Substring From String in Python

This tutorial is about how to remove substring from string in Python. It is impossible to change the strings in Python due to its immutability feature. However, an immutable string refers to a string that cannot be altered/deleted. Therefore, to bring changes to a mutable feature of a string, there is a need to create a new modified string after processing it through different computational methods. Removing a substring from a string can be difficult, but the process can be simplified with a few simple steps.

However, On this page, there will be a demonstration of how to easily remove a substring from a string in Python and with various examples of how this can be accomplished. So let’s get on the board!

Removing substring from the string in Python is quite crafty, and it becomes easier when done with a sharp approach. However, in different ways, it becomes easier to grab the part of a string and remove or delete it from the string in Python.

*working on Jupyter Notebook Anaconda Environment Python 3+ version.

If you want to learn more about python programming, visit Python Programming Tutorials.

replace() method to remove substring from a string in Python

replace() method is the first approach that comes while program execution to remove substring from a string in Python. However, Here the following example executes the whole process in the following steps:

  • The first step is to create a string and print it using the print command.
  • Now invoke the replace() method and pass at least two arguments in it. Additionally, Pass the characters you want to replace from the string. 
  • However, after computing, it will return the modified string containing the new characters after removing the substring characters from the strings. 
  • Here is how it executes!
#creating a string
New_Year= "The rabbit is the Chinese New Year's animal for 2023."
print("Original String:",New_Year)
#this will replace newline character with a whitespace
#String.replace(old, new, count)
New_Year.replace("Chinese New Year", 'CNY')
Original String: The rabbit is the Chinese New Year's animal for 2023.

"The rabbit is the CNY's animal for 2023."

Remove a Substring From a String in Python using the replace() function

Here is how to replace() function contributes to removing the sub-string from a string in Python. 

The syntax for the replace() function is:

Modified_string = my_String.replace(sub_string, “”)

where:

separator – is a character used to separate the strings, which are empty strings (“”) here in the following example.

sub_string– is the sub-strings that are being removed from the original string.

my_String = "For year 2022, Champion of the FIFA World Cup is Argentina."
sub_string = "For year 2022, "
Modified_string = my_String.replace(sub_string, "")
print("The input string is:", my_String)
print("The substring is:", sub_string)
print("\n")
print("The Modified string is:", Modified_string)
The input string is: For year 2022, Champion of the FIFA World Cup is Argentina.
The substring is: For year 2022, 


The Modified string is: Champion of the FIFA World Cup is Argentina.

len() function for removing substring from a string in Python

len() function is one of the approaches if we want to remove the characters from the beginning of the string. Here’s how it works:

  • Considering a string
  • Define a substring to be removed from the string within commas “….”.
  • Now within square brackets [ ] invoke len() function and pass the defined substring to it. And end the syntax with “ : “ 
  • It will print the modified string after removing the substring from a string in Python. 
# create a string
New_Year= "The rabbit is the Chinese New Year's animal for 2023."
# remove characters from the start of string
substring_to_be_removed = "The rabbit is"
# remove substring
New_Year[len(substring_to_be_removed):]
" the Chinese New Year's animal for 2023."

Negative index slicing approach 

Using negative index slicing, it becomes easy to remove substring characters from the string in Python. The index slicing approach is the most accessible approach to grab or remove any string characters in Python. endswith() will help to remove the end characters from the string. 

Here’s how it works:

  • Create a string and print it.
  • Define a substring from the string, which is to be removed. 
  • Using the if condition accomplished the job of removing substrings from the string in Python.
  • In the if expression invokes endswith() method with the original string using the (.) operator, pass the substring you want to remove from the string. 
  • In the if statement body, do the index slicing operations on the substring within square braces [ ].
# creating the string
flowers='Red Ginger,Tree Poppy,passion flower,water lily'
# printing an original String
print("Original String: ",flowers)
substring_to_be_removed = ',water lily'
# Remove substring using indexing approach
if flowers.endswith(substring_to_be_removed):
   flowers = flowers[ : -(len(substring_to_be_removed))]
# output
print("Modified String: ", flowers)
Original String:  Red Ginger,Tree Poppy,passion flower,water lily
Modified String:  Red Ginger,Tree Poppy,passion flower

re.sub() module for removing substring from a string in Python

The regex module in the python library will help us to remove the substring from the string in Python. The regex module will search and match the defined pattern with the original string and remove the pattern’s characters after matching them with the original string. 

Here’s how it works: 

  • Importing a regex (re) module from the python library.
  • Then create a string and print the original string.
  • Define a pattern that you want to remove, and here, in the following example, ‘$’ will be introduced to search and match the ending characters in the defined search patterns. 
  • If the condition qualifies, the string ends with characters defined within the substring. Using the re.sub() method in the Python re module, if True, will yield the result that is a modified string. 
  • Sub() takes three parameters, a regular expression pattern, an empty string that replaces all substrings that match the pattern, and the original string.
  • Substrings matching the given regex pattern are removed in the modified string. We will only match the end substring as we pass a regex pattern for this case.

Here’s how it executes the whole operation: 

#importing a regex module
import re
# making a string
flowers="Red Ginger,Tree Poppy,passion flower,water lily"
#print an original string
print("Original String: ",flowers)
substring_to_be_removed = ',water lily'
ptrn = substring_to_be_removed + "$"
# remove characters from the end of string
if flowers.endswith(substring_to_be_removed):
   flowers = re.sub(ptrn, '', flowers)
#Modified String
print("Modified String: ",flowers)
Original String:  Red Ginger,Tree Poppy,passion flower,water lily
Modified String:  Red Ginger,Tree Poppy,passion flower

Removing Substring From String in Python using Indexing

Using the Python language, we can remove a substring from a string. Moreover, Considering the limitation of Python syntax, we can’t change the string once it is created due to its mutable nature. However, we can still modify the original string. 

Here in the following example, we remove the substring from the string. However, Here is how it executes:

  • Considering a string
  • Now slice the string if you know the position of the characters or substring you want to exclude from the string. 
  • Here we slice the first 15 sub-string characters from the string.
  • And print our required modified string. 
my_String = "For year 2022, Champion of the FIFA World Cup is Argentina."
#incules whitespace
modified_string = myStr[15:]
print("The original string is:", my_String)
print("The Modified string is:", modified_string)
The original string is: For year 2022, Champion of the FIFA World Cup is Argentina.
The Modified string is: Champion of the FIFA World Cup is Argentina.

Here is the modified version of the string after removing the substring from the string, the string is changed using the str() function. Moreover, str() allow us to inject the string data-type characters within a string by keeping in mind the limitation of the Python language that string is immutable.

Here is how you remove a substring from a string in Python using the index function and modify your string in Python.

  • Considering any string
  • Now grab the string characters if the position of the string using indexing or slicing. 
  • Now step forward to remove the sub-string from the string. In the following example slicing from the start of the string. However, Count the position of the string, including whitespaces up to the index position you want to exclude from the modified string. 
  • Here in the following example [15:] “15” location is the characters we want in the final string, and “:” includes the last characters. 
  • After obtaining the indexing of considering string, now use the concatenation operator in aggregation with the str() function to modify the string.
my_String = "For year 2022, Champion of the FIFA World Cup is Argentina."
#incules whitespace while removing sub-string
modified_string = myStr[15:]
#add new characters in a string using str() function
final_string= str('Current ') + modified_string
print("The original string is:", my_String)
print("The Modified string is:", final_string)
The original string is: For year 2022, Champion of the FIFA World Cup is Argentina.
The Modified string is: Current Champion of the FIFA World Cup is Argentina.

Remove Substring From String in Python Using split() function

A split() function plays a role as a separator. It removes the substring from the string and separates the sub-string from the rest of the string. However, A separator string is passed as its input argument to the split() method on a string. Moreover, the split() function returns a list of substrings after the separator is applied to the original string. 

Here is how it executes:

  • Considering a string 
  • Defining a sub-string that we want to remove from the string.
  • Create an object of string data type and save the resultant output in that object.
  • The next step is to invoke the split() function and pass the argument (sub-string) to it. 
  • the split() function will translate the string in the list data type.
  • Now call for…in structure, and call split() list in the iterator. Therefore, whenever the iteration executes the iterator, it will join or concatenate each listed character and form it into the string.
  • And the output will then be saved in the variable created above. 
my_String = "For year 2022, Champion of the FIFA World Cup is Argentina."
#considering sub string from the original string
sub_string = "For year 2022, "
# to store the output in an object having a string data-type
output_of_string = ""
#invoking split() function
# split() function output will save in a list data-type
my_String_list = my_String.split(sub_string)
print(type(my_String_list))
#considering for...in structure
for characters in my_String_list:
# concatinate the strings
   output_of_string += characters
print(type(output_of_string))
print("The original string is:", my_String)
print("The sub string is:", sub_string)
print("The output of string is:", output_of_string)
<class 'list'>
<class 'str'>
The original string is: For year 2022, Champion of the FIFA World Cup is Argentina.
The sub string is: For year 2022, 
The output of string is: Champion of the FIFA World Cup is Argentina.

Using re.split() function to remove Substring From String in Python 

re.split() is a built-in function in Python that splits a string into a list of strings. Moreover, We can split any string with this function, but it is most commonly used to split strings on white space or non-alphanumeric characters.

However, the syntax for using re.split() is as follows:

my_String_list = re.split(pattern, String)

where:

  • my_String_list is the string to be split and the pattern is the regular expression you want to use to split your string.
  • However, the string is the string on which you want to split your regular expression (Regex) pattern.

The re.split() function is used to split a string into an array of strings, where each string contains the substring of the original string that matched the pattern specified in the first argument to re.split().

The re-module provides regular expression objects that can be used in string patterns. However, The following example uses these regular expressions to split a string into an array containing all of the words in a sentence:

  •  Import the regex module
  • Define the sub-string or pattern you want to remove from a string
  • Call the function and pass in the string to be searched for and the substring you want to be removed from it.
  • However, Using for…in an iterator to perform the iteration on my_String_list and save the result in the output_of_string using the concatenation operator. 
  • Print out the modified string.
import re
my_String = "For year 2022, Champion of the FIFA World Cup is Argentina."
sub_string = "For year 2022,"
output_of_string = ""
my_String_list = re.split(sub_string, my_String)
for i in my_String_list:
   output_of_string += i
  
print(type(my_String_list))
print(type(output_of_string))
print("The input string is:", my_String)
print("The substring is:", sub_string)
print("The output string is:", output_of_string)
<class 'list'>
<class 'str'>
The input string is: For year 2022, Champion of the FIFA World Cup is Argentina.
The substring is: For year 2022,
The output string is:  Champion of the FIFA World Cup is Argentina.

Using the join() function to remove a Substring from a string in Python

To remove a substring from a string in Python, you can use the join() function. therefore, Python has a handy function called join() that allows you to join string or tuples, etc, together into the string and concatenates them together.

Moreover, We can use this function to remove the “substring” from the original string by passing it as an argument to join().

The syntax for the join() function is:

modified_string = separator.join(my_String_list)

where

separator – is a character used to separate the strings here in the following example it is an empty string ‘’.

Here it executes the execution of join() function to remove a sub-string from a string in Python

  • Considering a string
  • Defining a sub-string
  • Invoking the split() function to separate the string from the substring, and save the output in the list.
  • join() will translate the list into the string data type.
  • However, the join() function takes my_String_list as an arguments, 
  • The my_String_list is to be joined with a separator (‘’).
  • And print the command to print the modified string. 
my_String = "For year 2022, Champion of the FIFA World Cup is Argentina."
sub_string = "For year 2022, "
modified_string= ""
my_String_list = my_String.split(sub_string)
modified_string = "".join(my_String_list)
print(type(my_String_list))
print(type(modified_string))
print("The input string is:", my_String)
print("The substring is:", sub_string)
print("The Modified string is:", modified_string)
<class 'list'>
<class 'str'>
The input string is: For year 2022, Champion of the FIFA World Cup is Argentina.
The substring is: For year 2022, 
The Modified string is: Champion of the FIFA World Cup is Argentina.

Conclusion

This page covers almost all targeted approaches, functions, and methods to remove substrings from strings in Python. However, Theses functions and methods includes re.sub() function, replace(), len(), and index sclicing approach, split() function, len(), replace(), re.split(), join() function.

If you want to learn more about Python Programming, Visit Python Programming Tutorials.

Leave a Comment

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