Python 如何从字符串末尾删除子字符串
在本文中,我们将了解如何在Python中从字符串末尾删除子字符串。
第一种方法是使用切片方法。在这种方法中,我们将检查字符串是否以给定的子字符串结尾,如果以给定的子字符串结尾,我们将使用切片方法删除子字符串。
在Python中,访问字符串、元组和列表等序列的部分被称为切片。此外,您还可以使用它们来添加、删除或编辑可变序列(如列表)的元素。切片也可以与Pandas系列、数据框和NumPy数组等外部对象一同使用。
示例
在下面的示例中,我们将一个字符串和一个子字符串作为输入,并使用切片方法从字符串末尾删除该子字符串。-
def remove_substr(str,sub):
if str.endswith(sub):
return str[:-len(sub)]
return str
str1 = "Welcome to Tutorialspoint"
print("The given string is ")
print(str1)
substr = "point"
print("The given substring is")
print(substr)
print("Removing the substring from the string")
print(remove_substr(str1,substr))
输出
上述示例的输出如下所示−
The given string is
Welcome to Tutorialspoint
The given substring is
point
Removing the substring from the string
Welcome to Tutorials
使用正则表达式的sub()方法
第二种方法是使用正则表达式的sub()方法。该方法需要三个参数:要替换的子字符串、将要替换的子字符串以及主字符串。所以我们将把末尾作为第一个参数,空字符串作为第二个参数,主字符串作为第三个参数。
示例
在下面给出的示例中,我们输入一个字符串和一个子字符串,并使用sub()方法将子字符串从末尾删除。
import re
def remove_substr(str,sub):
if str.endswith(sub):
res = re.sub(sub, '', str)
return res
return str
str1 = "Welcome to Tutorialspoint"
print("The given string is ")
print(str1)
substr = "point"
print("The given substring is")
print(substr)
print("Removing the substring from the string")
print(remove_substr(str1,substr))
输出
上述示例的输出结果如下所示−
The given string is
Welcome to Tutorialspoint
The given substring is
point
Removing the substring from the string
Welcome to Tutorials
使用replace()方法
第三种方法是使用 replace() 方法。这个方法接受两个参数,要替换的子字符串和我们要用来替换的子字符串。所以,在这里,要发送的第一个参数是结束的字符串,下一个参数将为空格。
示例
在下面的示例中,我们将一个字符串和一个子字符串作为输入,并使用replace方法从字符串的末尾移除子字符串。
def remove_substr(str,sub):
if str.endswith(sub):
res = str1.replace(sub, '')
return res
return str
str1 = "Welcome to Tutorialspoint"
print("The given string is ")
print(str1)
substr = "point"
print("The given substring is")
print(substr)
print("Removing the substring from the string")
print(remove_substr(str1,substr))
输出
上述示例的输出如下所示:
The given string is
Welcome to Tutorialspoint
The given substring is
point
Removing the substring from the string
Welcome to Tutorials