Skip to content
Related Articles

Related Articles

Python | Remove the given substring from end of string

Improve Article
Save Article
  • Last Updated : 27 Sep, 2022
Improve Article
Save Article

Sometimes we need to manipulate our string to remove extra information from the string for better understanding and faster processing. Given a task in which the substring needs to be removed from the end of the string using Python.   

Remove the substring from the end of the string using Slicing

In this method, we are using string slicing to remove the substring from the end.

Python3




text = 'GeeksforGeeksWorld'
sub = "World"
 
# find len of suffex
le = len(sub)
 
# slice out from string
text = text[:-le]
print(text)

Output:

GeeksforGeeks

Remove the substring from the end of the string using the Naive Method 

In this method, we are using the Python loop and append method to remove the substring from the end.

Python3




# Initialising string
ini_string = 'xbzefdgstb'
 
# initializing string
sstring = 'stb'
 
# printing initial string and substring
print ("initial_strings : ", ini_string, "\nsubstring : ", sstring)
 
# removing substring from end
# of string using Naive Method
if ini_string.endswith(sstring):
    res = ini_string[:-(len(sstring))]
 
# printing result
print ("resultant string", res)

Output:

initial_strings :  xbzefdgstb 
substring :  stb
resultant string xbzefdg

Remove the substring from the end of the string using sub() method 

In this method, we are using string regex sub() to remove the substring from the end.

Python3




import re
 
# Initialising string
ini_string = 'xbzefdgstb'
 
# initializing string
sstring = 'stb'
 
# printing initial string and substring
print ("initial_strings : ", ini_string, "\nsubstring : ", sstring)
 
# removing substring from end
# of string using sub Method
if ini_string.endswith(sstring):
    res = re.sub(sstring, '', ini_string)
 
# printing result
print ("resultant string", res)

Output:

initial_strings :  xbzefdgstb 
substring :  stb
resultant string xbzefdg

Remove the substring from the end of the string using replace() method 

In this method, we are using the string replace() function to remove the substring from the end.

Python3




# Initialising string
ini_string = 'xbzefdgstb'
 
# initializing string
sstring = 'stb'
 
# printing initial string and substring
print ("initial_strings : ", ini_string, "\nsubstring : ", sstring)
 
# removing substring from end
# of string using replace Method
if ini_string.endswith(sstring):
    res = ini_string.replace(sstring, '')
 
# printing result
print ("resultant string", res)

Output:

initial_strings :  xbzefdgstb 
substring :  stb
resultant string xbzefdg

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!