Python的strip()內置函數用於刪除字符串中的所有前導和尾隨空格。
用法:
string.strip([remove])
參數:
- remove (optional):字符或一組字符,需要從字符串中刪除。
該函數可以使用一個參數或不使用任何參數。如果未傳遞任何參數,則僅刪除前導和尾隨空格。
返回值:
The function returns another string with both leading and trailing characters being stripped off.
When the removed string matches perfectly then the modified string is returned with removed characters and spaces. When the remove string does not match then no modification is made to the original string.
下麵的代碼顯示strip()在各種條件下的工作。
代碼#1
# Python code to illustrate the working of strip()
string = ' Geeks for Geeks '
# Leading spaces are removed
print(string.strip())
# Geeks is removed
print(string.strip(' Geeks'))
# Not removed since the spaces do not match
print(string.strip('Geeks'))
輸出:
Geeks for Geeks for Geeks for Geeks
編碼#2
# Python code to illustrate the working of strip()
string = '@@@@Geeks for Geeks@@@@@'
# Strip all '@' from beginning and ending
print(string.strip('@'))
string = 'www.Geeksforgeeks.org'
# '.grow' removes 'www' and 'org' and '.'
print(string.strip('.grow'))
輸出:
Geeks for Geeks Geeksforgeeks
實際應用:
以下代碼顯示了strip()在python中的應用。
# Python code to check for identifiers
def Count(string):
print("Length before strip()")
print(len(string))
# Using strip() to remove white spaces
str = string.strip()
print("Length after removing spaces")
return str
# Driver Code
string = " Geeks for Geeks "
print(len(Count(string)))
輸出:
Length before strip() 17 Length after removing spaces 15
相關用法
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Python String | strip()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。