如何在Python中删除字符串末尾的子字符串?


在本文中,我们将了解如何在Python中删除字符串末尾的子字符串。

第一种方法是使用切片方法。在这种方法中,我们将检查字符串是否以给定的子字符串结尾,如果以给定的子字符串结尾,则我们将切片字符串,删除子字符串。

在Python中,访问字符串、元组和列表等序列的部分的能力被称为切片。此外,您可以使用它们来添加、删除或编辑可变序列(如列表)的元素。切片也可以与外部对象一起使用,例如Pandas序列、数据框和NumPy数组。

示例

在下面的示例中,我们以字符串和子字符串作为输入,并使用切片来删除字符串末尾的子字符串。

Open Compiler
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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

使用正则表达式的sub()方法

第二种方法是使用正则表达式的sub()方法。此方法接受3个参数:要替换的子字符串、将要替换成的子字符串和主字符串。因此,我们将把结尾作为第一个参数,空字符串作为第二个参数,主字符串作为第三个参数。

示例

在下面的示例中,我们以字符串和子字符串作为输入,并使用sub()方法删除末尾的子字符串。

Open Compiler
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()方法。此方法接受2个参数:要替换的子字符串和将要替换成的子字符串。因此,这里第一个参数是结尾,第二个参数是空字符串。

示例

在下面的示例中,我们以字符串和子字符串作为输入,并使用replace方法删除字符串末尾的子字符串。

Open Compiler
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

更新于:2022年12月7日

1K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告