美文网首页python专题
记一次python 字符串strip的使用问题

记一次python 字符串strip的使用问题

作者: 扯扯_2c79 | 来源:发表于2021-04-25 13:07 被阅读0次

首先请大家来看一下这行代码:

print("tmp-temp-test-pmt".strip(".tmp"))

你觉得输出的结果是什么?

我觉得大部分同学肯定会毫不犹豫的说答案是: -temp-test-pmt,相信大多数人都会觉得这个是没有问题的,然而事实情况却不是这样的,正确答案是:

-temp-test-

哈哈哈,奇怪吧,包括我最开始也很纳闷,还以为和python的版本有关系,或者说是一个BUG,但是其实结果却不是。

至于为什么是-temp-test-呢?我们来看一下strip函数的说明吧:

S.strip([chars]) -> string or unicode
        
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.
If chars is unicode, S will be converted to unicode before stripping

结果很明显,一切尽在不言中。通过文档我们可以知道strip函数的特点:

  • 如果未指定 chars 参数或参数值未 None, 去除字符串 首尾空白符(空格、换行符等等)

  • 否则,只要 首尾字符包含在 chars 定义的字符串内 ,就会被去除。并且会递归调用直到首尾字符不在 chars 内。类似:

def _strip(s, chars):
   if s[0] in chars:
       return _strip(s[1:], chars)
   elif s[-1] in chars:
       return _strip(s[:-1], chars)
   else:
       return s

此外更多的例子还有:


>>> '18349-13-3434'.strip('0123456789')
'-13-'

>>> '18349-13-3434'.strip('123')
'8349-13-3434'

>>> 'scene_scdefg'.strip('scene_')
'defg'

>>> '\r   \t\n '.strip()
''

现在我们知道 str.strip 是按 字符 进行移除操作的。 那么如何按字符串进行移除呢?

一种解决办法就是使用 re.sub:

def strip2(s, chars):
    re_chars = re.escape(chars)
    s = re.sub(r'^(?:%s)+(?P<right>.*)$' % re_chars, '\g<right>', s)
    s = re.sub(r'^(?P<left>.*?)(?:%s)+$' % re_chars, '\g<left>', s)
    return s

>>> print(strip2('12345-abc-12345-defg-54321', '12345'))
-abc-12345-defg-54321

相关文章

网友评论

    本文标题:记一次python 字符串strip的使用问题

    本文链接:https://www.haomeiwen.com/subject/sujdrltx.html