函数原型
Python中,strip()函数可实现对字符串头尾删除操作,lstrip()函数实现对字符串开头删除操作,rstrip()函数实现对字符串结尾处删除操作。函数源码附在文章最后
函数返回信息为删除操作后新的字符串,该操作不修改原有字符串信息
函数 | 描述 |
str.strip(ch) | 删除str字符串中开头,结尾处,ch子串信息 |
str.lstrip(ch) | 删除str字符串中开头处,位于ch子串信息 |
str.rstrip(ch) | 删除str字符串中结尾处,位于ch子串信息 |
示例
str = "000this is a string\texample,let's look if carefuly!0000"
print str.strip('0')
print str.lstrip('00')
print str.rstrip('00')
该段代码运行结果为:
"this is a string\texample,let's look if carefuly!"
"this is a string\texample,let's look if carefuly!0000"
"000this is a string\texample,let's look if carefuly!"
函数特别说明
入参为空默认删除空白符
如果strip函数的入参为空的话,默认删除空白符(包括'\n', '\r', '\t', ' ')
a = ' \n \t 123\n \r \t'
print a.strip()
上述示例返回的结果为
123
删除校验以字符为判断依据
如示例中,str.lstrip('00') 入参中给的是两个0,但实际返回的字符串中,左侧的三个0都执行了删除操作,这是因为该函数属于字符判断,只要左侧出现入参中的字符,就会被删除
c = "1212213abc3122122"
print c.strip('21')
print c.strip('12')
改操作执行后的结果为
3abc3
3abc3
strip()函数源码
def strip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.strip([chars]) -> str
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return ""
strip(ch)函数源码
def strip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.strip([chars]) -> str
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return ""
lstrip()函数源码
def lstrip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.lstrip([chars]) -> str
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return ""
lstrip(ch)函数源码
def lstrip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.lstrip([chars]) -> str
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return ""
rstrip()函数源码
def rstrip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.rstrip([chars]) -> str
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return ""
rstrip(ch)函数源码
def rstrip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.rstrip([chars]) -> str
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return ""