python专题

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

2021-04-25  本文已影响0人  扯扯_2c79

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

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函数的特点:

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
上一篇 下一篇

猜你喜欢

热点阅读