如何在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
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP