Skip to content

Instantly share code, notes, and snippets.

@elowy01
Last active July 22, 2022 11:36
Show Gist options
  • Save elowy01/edcebad7ca1e5145a362f9274218a7a4 to your computer and use it in GitHub Desktop.
Save elowy01/edcebad7ca1e5145a362f9274218a7a4 to your computer and use it in GitHub Desktop.
############### Method 1:
# 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)
#### Method #2: Using sub() method
# 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)
####### # 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment