Python程式:從右側修剪字串
在Python中,我們有一個預定義函式`rstrip()`用於刪除右側的字元。這意味著它將刪除字串右側的空格。
讓我們來看一個例子,瞭解如何從左側修剪字串。
在給定的字串“WIRELESS”中,刪除右側字串LESS,得到結果值“WIRE”。
在給定的字串“kingdom”中,刪除右側字串dom,得到結果值“king”。
語法
示例中使用的語法如下:
isspace()
這是一個在Python中使用的預定義方法,允許在字元中使用空格、換行符或其他空格。
rstrip("parameter as a string")
這是一個在Python中使用的預定義方法,它接受字元作為引數,用於從字串右側刪除字元。
endswith()
這是一個Python內建方法,如果字串以特定值結尾,則返回True。
示例1
在這個程式中,我們將輸入字串儲存在變數‘str’中。然後將變數‘i’初始化為值5,稍後將修剪第5個索引之後的字元。接下來,變數‘str’使用for迴圈遍歷變數‘char’。然後使用if語句使用isspace()方法搜尋空格。如果在字串中找不到空格,它將中斷迴圈,並且變數‘i’為每個空格字元遞減。現在我們使用str[:i]修剪字元,並將值儲存在變數‘trim_str’中。最後,我們使用變數‘trim_str’列印結果。
#trim the string from the right
str = "UNIVERSITY"
i = 5
for char in str:
if not char.isspace():
break
i -= 1
trim_str = str[:i] #The use before slicing removes the right string.
print("Trim the string of", i," characters from right:", trim_str)
輸出
Trim the string of 5 characters from right: UNIVE
示例2
在這個程式中,我們將輸入字串儲存在變數‘my_str’中。然後我們從字串的右側修剪字元'a',並將其儲存在變數‘trim_str’中。最後,我們使用變數‘trim_str’列印結果。
#Trim the string from right
my_str = "aaaaa!King!aaaaa"
trim_str = my_str.rstrip("a")
print(trim_str)
輸出
aaaaa!King!
示例3
在這個程式中,我們將開始將輸入字串儲存在變數str_name中。然後將右側要刪除的字串儲存在變數del_suffix中。然後應用if語句來檢查使用內建方法endswith()從右側刪除字串的條件。接下來,使用replace()方法刪除給定的字串並將其儲存在變數str_name中。最後,我們使用str_name列印變數。
str_name = "abcdefghi"
del_suffix = "ghi"
if str_name.endswith(del_suffix):
str_name = str_name.replace(del_suffix, "")
print("After deleting the suffix from left side:",str_name)
輸出
After deleting the suffix from left side: abcdef
示例4
在下面的程式中,我們將輸入字串儲存在變數s中。然後使用內建方法removesuffix(),設定名為‘iop’的字串,從右側刪除字串,並使用print()函式列印結果。
s = 'qwertyuiop'
print(s.removesuffix('iop'))
輸出
qwertyu
結論
我們透過從左側修剪字串瞭解了這兩個示例之間的區別。我們看到示例中使用了多種不同的方法,包括isspace()、rstrip()、endswith()和切片技術。切片技術通常用於從右側修剪字串。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP