Python | Remove the given substring from end of string
Last Updated :
13 Mar, 2023
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"
le = len (sub)
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
ini_string = 'xbzefdgstb'
sstring = 'stb'
print ( "initial_strings : " , ini_string, "\nsubstring : " , sstring)
if ini_string.endswith(sstring):
res = ini_string[: - ( len (sstring))]
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
ini_string = 'xbzefdgstb'
sstring = 'stb'
print ( "initial_strings : " , ini_string, "\nsubstring : " , sstring)
if ini_string.endswith(sstring):
res = re.sub(sstring, '', ini_string)
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
ini_string = 'xbzefdgstb'
sstring = 'stb'
print ( "initial_strings : " , ini_string, "\nsubstring : " , sstring)
if ini_string.endswith(sstring):
res = ini_string.replace(sstring, '')
print ( "resultant string" , res)
|
Output
initial_strings : xbzefdgstb
substring : stb
resultant string xbzefdg
Using rfind() and slicing
rfind() returns the index of the last occurrence of the substring in the string. Then we slice the string from the beginning up to the index of the substring.
Python3
text = 'GeeksforGeeksWorld'
sub = "World"
index = text.rfind(sub)
text = text[:index]
print (text)
|
Time complexity: O(n), where n is the length of the string.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...