Change language

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 

Python | Remove the specified substring from the end of the string Python functions: Questions

Python | Remove the specified substring from the end of the string String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method