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

2024-04-25 19:52:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近意识到,Python的strip内置函数(它的子函数rstriplstrip)并没有把给它的字符串当作一个有序的字符序列来处理,而是把它当作一种字符的“存储库”:

>>> s = 'abcfooabc'
>>> s.strip('abc')
'foo'
>>> s.strip('cba')
'foo'
>>> s.strip('acb')
'foo'

等等。

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


Tags: 函数字符串foo序列字符内置stripabc
3条回答

这个呢: s.split('abc')

返回:['', 'foo', '']

因此,我们可以将其更改为:

[i for i in s.split('abc') if i != '']。如果你只想要'foo',而不是['foo'],你可以这样做:[i for i in s.split('abc') if i != ''][0]

一起:

def splitString(s, delimiter):
    return [i for i in s.split(delimiter) if i != ''][0]

我刚开始的时候也有同样的问题。

改为尝试str.replace

>>> s = 'abcfooabc'
>>> s.replace("abc", "")
0: 'foo'
>>> s.replace("cba", "")
1: 'abcfooabc'
>>> s.replace("acb", "")
2: 'abcfooabc'

我不知道什么是内置的,不,但很简单:

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

相关问题 更多 >