Python 程式用於從左側修剪字串


Python 具有各種內部函式,例如 isspace()、lstrip() 和 replace() 用於修剪給定的字串。這意味著它將刪除字串左側的空格。

讓我們舉個例子來理解從左側修剪字串。

  • 在給定的字串“MICROBOX”中,刪除左側字串 MI 並得到結果值“CROBOX”。

  • 在給定的字串“synapse”中,刪除左側字串 syn 並得到結果值“apse”。

在本文中,我們將學習如何開發一個 Python 程式,該程式將從左側修剪字串。

語法

示例中使用的以下語法為:

isspace()

這是一種在 Python 中使用的預定義方法,允許在字元中使用空格、換行符或空格。

lstrip("parameter as a string")

這是一種在 Python 中使用的預定義方法,它接受字元作為引數,以從左側刪除字串的字元。

startswith()

這是一種 Python 中的內建方法,可用於設定字串的左側以識別給定的字串。

示例 1

在此程式中,我們將輸入字串儲存在變數‘str’中。然後將變數‘i’初始化為值4,這將從左側修剪總共 4 個字元。接下來,變數‘str’使用 for 迴圈遍歷變數‘char’。然後使用 if 語句透過使用isspace()方法搜尋空格。如果在字串中找不到空格,它將中斷迴圈,並且變數‘i’為每個空格字元遞增。現在我們使用str[i:]修剪字元並將值儲存在變數‘trim_str’中。最後,我們藉助變數‘trim_str’列印結果。

#trim the string from left
str = "My school"
i = 4
for char in str:
   if not char.isspace():
      break
   i += 1
trim_str = str[i:] #The use after slicing remove the left string.
print("Trim the string of", i,"character from left:",trim_str)

輸出

Trim the string of 4 character from left: chool

示例 2

在此程式中,我們將輸入字串儲存在變數‘my_str’中。然後建立新的變數‘trim_str’以透過刪除修剪字元來儲存值。lstrip()方法從左側刪除字元。最後,我們藉助變數‘trim_str’列印結果。

#Trim the string from left
my_str = "SCHOOL"
trim_str = my_str.lstrip("SC")
print(trim_str)

輸出

HOOL

示例 3

在此程式中,我們首先將輸入字串儲存在變數str_name中。然後在變數l_suffix中設定要從左側刪除的字串。現在,開始使用 if 語句檢查給定字串與內建函式startswith()的條件,該函式將查詢要刪除的字尾。接下來,使用給定字串的 len() 方法進行切片並將其儲存在變數str_name中。最後,列印變數str_name中其餘字串的結果。

str_name = "asdfghjkl"
l_suffix = "asd"
if str_name.startswith(l_suffix):
   str_name = str_name[len(l_suffix):]
print("After deleting the suffix from the left side:",str_name)

輸出

After deleting the suffix from the left side: fghjkl

示例 4

在以下程式中,我們首先將輸入字串儲存在變數 str_name 中。然後在變數del_suffix中設定要刪除的左側字串。然後使用 if 語句檢查使用內建方法 startswith() 刪除字串的條件。接下來,使用名為 replace() 的方法,該方法接受兩個引數 - l_suffix(刪除)和空字串“”來儲存其餘字串。最後,我們藉助變數str_name列印結果。

str_name = "abcdefghi"
l_suffix = "abcde"
if str_name.startswith(l_suffix):
   str_name = str_name.replace(l_suffix, "")
print("After deleting the suffix from the left side:",str_name)

輸出

After deleting the suffix from the left side: fghi

結論

我們透過從左側修剪字串瞭解了這兩個示例之間的區別。我們看到示例中使用了兩種不同的方法,分別是 isspace() 和 lstrip()。在示例 1 中,我們使用了冒號“:”後面的內容來從左側刪除字串。

更新於: 2023年6月1日

224 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.