Python | Remove the given substring from end of string

Sometimes we need to manipulate our string to remove extra information from string for better understanding and faster processing. Given a task in which substring needs to be removed from the end of the string. Given below are a few methods to solve the given task.
 

Method #1: Using Naive Method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# to remove a substring from end of the string
  
# 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)

chevron_right


Output:



initial_strings :  xbzefdgstb 
substring :  stb
resultant string xbzefdg

 
Method #2: Using sub() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# to remove a substring from end of string
  
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)

chevron_right


Output:

initial_strings :  xbzefdgstb 
substring :  stb
resultant string xbzefdg

 
Method #3: Using replace() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# to remove a substring from end of string
  
# 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)

chevron_right


Output:

initial_strings :  xbzefdgstb 
substring :  stb
resultant string xbzefdg


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.