搜尋
首頁後端開發Python教學使用Python從字串的末尾刪除給定的子字串

使用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

重新模組

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 模組刪除字串末尾存在的子字串的另一種方法。捕獲組與正規表示式模組一起使用來刪除子字串。使用捕獲組刪除子字串的程式碼和範例如下:

範例

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 從字串末尾刪除子字串。可能還有其他方法可以刪除子字串,但本文提到的方法是建議的最短和最簡單的方法,您可以根據您的應用程式領域進行選擇。

以上是使用Python從字串的末尾刪除給定的子字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除
列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

說明如何將內存分配給Python中的列表與數組。說明如何將內存分配給Python中的列表與數組。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python數組中指定元素的數據類型?您如何在Python數組中指定元素的數據類型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什麼是Numpy,為什麼對於Python中的數值計算很重要?什麼是Numpy,為什麼對於Python中的數值計算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

討論'連續內存分配”的概念及其對數組的重要性。討論'連續內存分配”的概念及其對數組的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。