strip()是Python編程語言中的內置函數,該函數返回刪除了前導和尾隨字符的字符串的副本(基於傳遞的字符串參數)。
用法:
string.strip([chars])
參數:
There is only one optional parameter in it:
1)chars - a string specifying
the set of characters to be removed.
If the optional chars parameter is not given, all leading
and trailing whitespaces are removed from the string.
返回值:
Returns a copy of the string with both leading and trailing characters removed.
# Python3 program to demonstrate the use of
# strip() method
string = " geeks for geeks "
# prints the string without stripping
print(string)
# prints the string by removing leading and trailing whitespaces
print(string.strip())
# prints the string by removing geeks
print(string.strip(' geeks'))
輸出:
geeks for geeks geeks for geeks for
錯誤:
當我們嘗試剝離字符串以外的任何內容時,都會出現運行時錯誤。係統給出的輸出顯示
# Python3 program to demonstrate the use of
# strip() method error
string = " geeks for geeks "
list =[1, 2, 3]
# prints the error message
print(list.strip())
輸出:
Traceback (most recent call last): File "/home/1bdead5a6ad1dbb0db1c6a2663874e4c.py", line 8, in print(list.strip()) AttributeError:type object 'list' has no attribute 'strip'
實際應用:
給定一個字符串,請從開頭和結尾刪除單詞“The”的出現。
# Python3 program to demonstrate the practical application
# strip()
string = " the King has the largest army in the entire world the"
# prints the string after removing the from beginning and end
print(string.strip(" the"))
輸出:
King has the largest army in the entire world
相關用法
注:本文由純淨天空篩選整理自Striver大神的英文原創作品 Python string | strip()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。