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