Python之去掉字符串空格(strip)


正文:


Python去掉字符串空格有三个函数:


strip 同时去掉字符串左右两边的空格;
lstrip 去掉字符串左边的空格;
rstrip 去掉字符串右边(末尾)的空格;

详细解读:


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

  • strip函数:s.strip(re)
    1,用于删除s字符串中开头处、结尾处、位于re删除序列的字符
    2,当re为空时,strip()默认是删除空白符(包括‘\n’,‘\r’,‘\t’,‘’),例如:
>>>a = '    abc'
>>>a.strip()
'abc'
>>>a = '\t\t\nabc'
>>>a.strip()
'abc'
>>>a = '  abc\r\t'
>>>a.strip()
'abc'

3,这里我们说的re删除序列是只要满足re的开头或者结尾上的字符在删除序列内,就能删除掉,比如说:

>>> a = 'abc123'
>>>>a.strip('342')
'abc1'
>>>a.strip('234')
'abc1'

可以看出结果是一样的。

  • lstrip函数:s.lstrip(re),用于删除s字符串中开头处,位于re删除序列中的字符,比如:
>>>a = "    this is string example.....wow!!!   "
>>>a.lstrip()
'this is string example.....wow!!!   '
>>>a = "88888888this is string example....wow!!!8888888"
>>>a.lstrip('8')
'this is string example....wow!!!8888888'
  • rstrip函数:s.rstrip(re),用于删除s字符串中结尾处,位于re删除序列的字符,比如:
>>>a = "    this is string example.....wow!!!   "
>>>a.rstrip()
'    this is string example.....wow!!!'
>>>a = "88888888this is string example....wow!!!8888888"
>>>a.rstrip('8')
'8888888this is string example....wow!!!'

OK!到此结束啦,不知道你了解了没???^-^

猜你喜欢

转载自blog.csdn.net/huacode/article/details/79942237