Python程式:刪除給定字串的字尾


在Python中,我們有一些內建的字串函式,例如rstrip()、replace()和endswith(),可以用來刪除給定字串的字尾。刪除字尾是指刪除字串末尾的一組字元。有時我們會發現資料中存在類似字尾的錯誤,如果我們想刪除它,會花費大量時間,這可以透過給出演算法來解決。結尾字元或子串稱為字尾。

讓我們透過一個例子來理解這一點:

給定的字串變數是BRIGHTNING,刪除字尾NING後,該單詞變為BRIGHT。

語法

endswith()

這是Python中預定義的方法,如果字串以給定值結尾,則返回true,否則返回false。

rstrip()

這是Python中預定義的方法,它從字串末尾刪除給定的字尾字元。

replace(“replace_string_var_name”,  “”)

這是一個Python中的內建方法,它接受兩個引數:

  • replace_string_var_name - 指明變數的名稱。

  • 空字串 - 空字串用“”表示,它儲存給定字串中其餘的子字串。

演算法

  • 我們正在獲取輸入字串變數。

  • 然後我們使用if語句來設定預定義的方法,即endswith,並使用輸入字串變數來獲取字尾子字串。如果找到子字串在結尾,則返回true,否則返回false。(示例1和示例2)

  • 然後我們使用預定義的方法,即rstrip,以及輸入字串變數。此方法從末尾刪除字串。(示例3)

  • 然後使用if語句檢查使用endswith()函式刪除子字串的條件。(示例4)

  • 接下來計算字尾子字串的長度操作,並執行以下操作:

    • str_name = str_name[:-len("car")] - 透過這種表示方法,我們用減號表示給定字尾子字串的長度。(示例1)

    • str_name = str_name[:len(str_name)-len(suffix_name)] - 透過這種表示方法,我們從給定字串中減去字串的長度。(示例2)

    • 接下來,使用replace方法替換指定的字串並獲取結果。(示例4)

    • 因此,我們將以此方式刪除字尾子字串。

  • 最後,我們藉助輸入字串變數列印結果。

示例1

在這個程式中,我們使用預定義函式endswith()來設定字尾字串,並透過表示減號“-”來刪除字尾的長度,然後獲取結果。

str_name = "RANSOMEWARE"
if str_name.endswith("car"):
   str_name = str_name[ :-len("WARE") ]
print( "After deleting the given suffix:", str_name )

輸出

After deleting the given suffix: RANSOME

示例2

在這個程式中,我們採用兩個變數——輸入字串和字尾字串,然後使用預定義函式endswith()設定字尾字串。為了刪除字尾子字串,我們從給定字串變數的總長度中減去後綴變數的長度。

str_name = "Doctorate"
suffix_name = "ate"
if str_name.endswith( suffix_name ):
   str_name = str_name[ :len(str_name)-len(suffix_name) ]
print( "After deleting the given suffix:", str_name )

輸出

After deleting the given suffix: Doctor

示例3

在這個程式中,我們使用預定義函式rstrip()從給定字串中刪除字尾子字串並獲取結果。

str_name = "Rectangle"
str_name = str_name.rstrip( "gle" )
print( "After deleting the given suffix:", str_name )

輸出

After deleting the given suffix: Rectan

示例4

在下面的示例中,我們將開始將輸入字串儲存在變數str_name中。然後將要刪除的子字串儲存在變數del_suffix中。然後使用if語句檢查使用內建方法endswith()的字串刪除條件。接下來,使用接受兩個引數的replace方法- del_suffix(刪除子字串)和""(空字串,用於儲存其餘字串)。然後使用變數del_suffix列印結果。

str_name = "abcdefghi"
del_suffix = "ghi"
if str_name.endswith(del_suffix):
   str_name = str_name.replace(del_suffix, "")
print("After delete the substring from the given string:",str_name)

輸出

After deleting the substring from the given string: abcdef

結論

我們探討了從給定字串中刪除字尾子字串的概念。我們看到了這個程式的三個示例,並且解決方法透過採用長度運算和預定義方法而有所不同。這種型別的程式通常用於刪除以相同字尾結尾的多個單詞。

更新於:2023年6月1日

2K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告