使用 Python 从字符串末尾移除给定子字符串


Python 是一种全球广泛使用的编程语言,开发者将其用于各种目的。Python 拥有各种不同的应用,例如 Web 开发、数据科学、机器学习,以及执行自动化流程。所有使用 Python 的程序员都需要处理字符串和子字符串。因此,本文将学习如何移除字符串末尾存在的子字符串。

移除子字符串的不同方法

使用函数

我们将使用 endswith() 函数,它可以帮助我们移除字符串末尾存在的子字符串。为了更清楚地理解它,我们将以下面的示例为例

示例

def remove_substring(string, substring):  #Defining two different parameters
    if string.endswith(substring):
        return string[:len(string)-len(substring)]   #If substring is present at the end of the string then the length of the substring is removed from the string
    else:
        return string   #If there is no substring at the end, it will return with the same length

# Example 
text = "Hello Everyone, I am John, The Sailor!"
last_substring = ", The Sailor!" #Specifying the substring
#Do not forget to enter the last exclamation mark, not entering the punctuations might lead to error
Without_substring = remove_substring(text, last_substring)
print(Without_substring)

输出

上述代码的输出如下所示

Hello Everyone, I am John

字符串切片

在此方法中,我们将切片字符串末尾存在的子字符串。Python 提供了切片代码中文本或字符串的功能。我们将在程序中定义子字符串,并相应地对其进行切片。以下是用此方法移除子字符串的代码以及示例

示例

def remove_substring(string, substring):
    if string[-len(substring):] == substring:  #The length of last characters of the string (length of substring) is compared with the substring and if they are same the substring is removed 
        return string[:-len(substring)]  
    else:
        return string  #If the length of last characters(Substring) does not match with the length of last substring then the characters are not removed 

# Example 
Whole_string = "Hello Everyone, I am John, the Sailor!"
last_substring = ", the Sailor!"
Final_String = remove_substring(Whole_string, last_substring)
print(Final_String)

输出

上述代码的输出如下所示

Hello Everyone, I am John

re 模块

Python 编程语言内置的 re 模块用于处理正则表达式。我们可以使用 re 模块的一个函数来移除字符串末尾的子字符串。我们将使用的函数是 re.sub() 函数。以下是用 re 模块函数移除字符串最后一个子字符串的代码和示例

示例

import re  #Do not forget to import re module or it might lead to error while running the program

def remove_substring(string, substring):
    pattern = re.escape(substring) + r'$'  #re.escape is used to create a pattern to treat all symbols equally and it includes $ to work only on the substring on the end of the string
    return re.sub(pattern, '', string)  #This replaces the last substring with an empty space

# Example
Whole_string = "Hello Everyone, I am John, the Sailor!"
last_substring = ", the Sailor!"
Final_String = remove_substring(Whole_string, last_substring)
print(Final_String)

输出

上述代码的输出如下所示

Hello Everyone, I am John

切片与函数结合

在这种情况下,我们将使用 rfind() 函数,它从右侧开始查找定义的子字符串,然后我们可以借助切片功能移除子字符串。您可以通过以下示例更好地理解它

示例

def remove_substring(string, substring):
    index = string.rfind(substring)  #rfind() is used to find the highest index of the substring in the string
    if index != -1 and index + len(substring) == len(string):    # If a substring is found, it is removed by slicing the string
        return string[:index]
    else:
        return string   #If no substring is found the original string is returned

# Example 
Whole_string = "Hello Everyone, I am John, the Sailor!"
last_substring = ", the Sailor!"
Final_String = remove_substring(Whole_string, last_substring)
print(Final_String)

输出

上述代码的输出如下所示

Hello Everyone, I am John

带捕获组的 re 模块

这是使用 re 模块移除字符串末尾存在的子字符串的不同方法。捕获组与正则表达式模块一起使用,以移除子字符串。以下是用捕获组移除子字符串的代码和示例

示例

import re #Do not forget to import the re module or error might occur while running the code

def remove_substring(string, substring):
    pattern = re.escape(substring) + r'(?=$)' # A function is created first and re.escape is used so that all the functions are created equally
    return re.sub(pattern, '', string) # With the help of re.sub() function, the substring will be replaced with empty place

# Example 
Whole_string = "Hello Everyone, I am John, the Sailor!"
last_substring = ", the Sailor!"
Final_String = remove_substring(Whole_string, last_substring)
print(Final_String)

输出

上述代码的输出如下所示

Hello Everyone, I am John

结论

在全球范围内的所有用户中,对字符串进行修改的需求非常普遍,但很多时候,如果未采用正确的方法,移除字符串的过程可能会花费大量时间。因此,本文介绍了上述许多不同的方法,这些方法可用于使用 Python 从字符串末尾移除子字符串。可能还有其他方法可以移除子字符串,但本文中提到的方法是最短和最简单的方法,您可以根据您的应用领域选择其中一种。

更新于: 2023年8月1日

69 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告