从字符串中删除有序的字符序列

mic*_*yer 8 python strip python-3.x

我最近意识到strip的Python(和它的孩子们的内置rstriplstrip)不治疗是给予它作为参数作为一个字符的有序序列串,而是作为一种字符的"蓄水池"的:

>>> s = 'abcfooabc'
>>> s.strip('abc')
'foo'
>>> s.strip('cba')
'foo'
>>> s.strip('acb')
'foo'
Run Code Online (Sandbox Code Playgroud)

等等.

有没有办法从给定的字符串中删除有序子字符串,以便在上面的示例中输出会有所不同?

bba*_*les 7

刚开始时,我也遇到过同样的问题。

尝试使用str.replace吗?

>>> s = 'abcfooabc'
>>> s.replace("abc", "")
0: 'foo'
>>> s.replace("cba", "")
1: 'abcfooabc'
>>> s.replace("acb", "")
2: 'abcfooabc'
Run Code Online (Sandbox Code Playgroud)

  • OP 似乎对剥离和替换之间的区别感到困惑。`"fooabcfoo"` 的预期输出是什么? (2认同)

jts*_*ven 6

从 Python 3.9 开始,您可以使用str.removeprefixstr.removesuffix

来自文档:

'TestHook'.removeprefix('Test')  # >> 'Hook'
'MiscTests'.removesuffix('Tests')  # >> 'Misc'
Run Code Online (Sandbox Code Playgroud)


ick*_*fay 5

我不知道内置的方式,不,但它很简单:

def strip_string(string, to_strip):
    if to_strip:
        while string.startswith(to_strip):
            string = string[len(to_strip):]
        while string.endswith(to_strip):
            string = string[:-len(to_strip)]
    return string
Run Code Online (Sandbox Code Playgroud)