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
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
# Python3 code to demonstrate# to remove a substring from end of the string # Initialising stringini_string = 'xbzefdgstb' # initializing stringsstring = 'stb' # printing initial string and substringprint ("initial_strings : ", ini_string, "\nsubstring : ", sstring) # removing substring from end# of string using Naive Methodif ini_string.endswith(sstring): res = ini_string[:-(len(sstring))] # printing resultprint ("resultant string", res) |
initial_strings : xbzefdgstb substring : stb resultant string xbzefdg
Method #2: Using sub() method
# Python3 code to demonstrate# to remove a substring from end of string import re # Initialising stringini_string = 'xbzefdgstb' # initializing stringsstring = 'stb' # printing initial string and substringprint ("initial_strings : ", ini_string, "\nsubstring : ", sstring) # removing substring from end# of string using sub Methodif ini_string.endswith(sstring): res = re.sub(sstring, '', ini_string) # printing resultprint ("resultant string", res) |
initial_strings : xbzefdgstb substring : stb resultant string xbzefdg
Method #3: Using replace() method
# Python3 code to demonstrate# to remove a substring from end of string # Initialising stringini_string = 'xbzefdgstb' # initializing stringsstring = 'stb' # printing initial string and substringprint ("initial_strings : ", ini_string, "\nsubstring : ", sstring) # removing substring from end# of string using replace Methodif ini_string.endswith(sstring): res = ini_string.replace(sstring, '') # printing resultprint ("resultant string", res) |
initial_strings : xbzefdgstb substring : stb resultant string xbzefdg

