如何在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()方法。此方法接受3个参数:要替换的子字符串,用于替换的子字符串,以及主字符串。因此,我们将发送结尾作为第一个参数,空字符串作为第二个参数,主字符串作为第三个参数。

示例

在下面的示例中,我们以字符串和子字符串作为输入,并使用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()方法。此方法接受2个参数:要替换的子字符串和用于替换的子字符串。因此,这里发送的第一个参数是结尾,第二个参数是空字符串。

示例

在下面的示例中,我们以字符串和子字符串作为输入,并使用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

更新于:2022年12月7日

1K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.