Last active
July 22, 2022 11:36
-
-
Save elowy01/edcebad7ca1e5145a362f9274218a7a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
############### 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