Python|从字符串末尾删除给定的子字符串
有时我们需要操纵我们的字符串以从字符串中删除额外的信息,以便更好地理解和更快地处理。给定一个需要从字符串末尾删除子字符串的任务。下面给出了一些解决给定任务的方法。
方法#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)
输出:
initial_strings : xbzefdgstb
substring : stb
resultant string xbzefdg
方法#2:使用sub()
方法
# 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)
输出:
initial_strings : xbzefdgstb
substring : stb
resultant string xbzefdg
方法 #3:使用replace()
方法
# 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)
输出:
initial_strings : xbzefdgstb
substring : stb
resultant string xbzefdg