Python | Remove the specified substring from the end of the string

Method # 1: Using the naive method

# Python3 demo code
# remove a substring from the end of the line

 
# Initializing string

ini_string = `xbzefdgstb`

 
# initialization string

sstring = `stb`

 
# print start line and substring

print ( "initial_strings:" , ini_str ing, "substring:" , sstring)

 
# removing a substring from the end
# using the Naive method

if ini_string.endswith (sstring):

res = ini_string [: - ( len (sstring) )]

 
# print result

print ( "resultant string" , res)

Exit:

 initial_strings: xbzefdgst b substring: stb resultant string xbzefdg 

Method # 2: Using the sub()

Output :

 initial_strings: xbzefdgstb substring: stb resultant string xbzefdg 

Method # 3: Using the method replace()

# Python3 demo code
# remove substring from end of line

 

import re

 
# Initialization string

ini_string = `xbzefdgstb`

  
# initialization string

sstring = `stb`

  
# print start real string and substrings

print ( " initial_strings: " , ini_string, " substring: " , sstring)

 
# remove a substring from the end
# strings using the sub method

if ini_string.endswith (sstring) :

res = re.sub (sstring, ``, ini_string)

 
# print result

print ( "resultant string" , res)

# Python3 demo code
# remove a substring from the end of the line

  
# Initializing string

ini_string = `xbzefdgstb`

 
# initialization string

sstring = `stb`

  
# print start line and substring

print ( "initial_strings:" , ini_string, "substring:" , sstring)

  
# removing a substring from the end
# using the replace method

if ini_string.endswith (sstring):

res = ini_string.replace (sstring,` `)

 
# print result

print ( "resultant string" , res)

Exit:

 initi al_strings: xbzefdgstb substring: stb resultant string xbzefdg