首頁  >  文章  >  後端開發  >  Python程式從給定字串中刪除後綴

Python程式從給定字串中刪除後綴

WBOY
WBOY轉載
2023-08-30 09:21:071134瀏覽

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)

    • #所以,這樣我們就刪除了後綴子字串。

  • 最後,我們在輸入字串變數的幫助下列印結果。

Example 1

的中文翻譯為:

範例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

Example 3

的中文翻譯為:

範例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

Example 4

的中文翻譯為:

範例 4

在下面的範例中,我們將開始將輸入字串儲存在變數 str_name 中。然後將刪除的子字串儲存在變數del_suffix中。然後使用 if 語句使用內建方法endswith() 檢查字串刪除的條件。接下來,使用接受兩個參數的替換方法 - 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

結論

我們探索了從給定字串中刪除後綴子字串的概念。我們看到這個程式有3個例子,求解的方式不同,分別採用長度運算和預先定義的方法。此類程式通常用於刪除以相同後綴結尾的多個單字。

以上是Python程式從給定字串中刪除後綴的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除