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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。