如何在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
廣告