使用 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 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.