strip()函数使用

str. strip ( [ chars ] )

函数原型

声明:s为字符串,rm为要删除的字符序列

s.strip(rm)    删除s字符串中开头、结尾处,位于 rm删除序列的字符


Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

>>> '   spacious   '.strip()'spacious'>>> 'www.example.com'.strip('cmowz.')'example'

The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example:

>>> comment_string='#....... Section 3.2.1 Issue #32 .......'>>> comment_string.strip('.#! ')'Section 3.2.1 Issue #32'

strip的过程:
从头到尾扫描字符串,只要它在chars中就移除,直到遇到不在chars中的字符串停止,接着 从尾到头扫描字符串,只要它在chars中就移除,直到遇到不在chars中的字符串停止

注意:
1. 当rm为空时,默认删除空白符(包括'\n', '\r',  '\t',  ' ')
例如:
代码如下:

>>> a = '     123'
>>> a.strip()
'123'
>>> a='\t\tabc'
'abc'
>>> a = 'sdff\r\n'
>>> a.strip()
'sdff'
2.这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。
例如 :
代码如下:

>>> a = '123abc'
>>> a.strip('21')
'3abc'   结果是一样的
>>> a.strip('12')
 
            
'3abc'


你可能感兴趣的:(Python)