使用默认分隔符与用户定义的分隔符拆分的字符串

String split with default delimiter vs user defined delimiter

我尝试了一个简单的字符串拆分示例,但出现了一些意外行为。这是示例代码:

def split_string(source,splitlist):
    for delim in splitlist:
        source = source.replace(delim, ' ')
    return source.split(' ')

out = split_string("This is a test-of the,string separation-code!", " ,!-")
print out
>>> ['This', 'is', 'a', 'test', 'of', 'the', 'string', 'separation', 'code', '']

如您所见,当我使用 space 作为 split() 函数的分隔符参数时,列表末尾多了一个空字符串。但是,如果我不为 split() 函数传入任何参数,则输出列表末尾没有空字符串。

根据我在 python 文档中阅读的内容,他们说 split() 的默认参数是 space。那么,为什么当我显式传入一个 ' ' 作为分隔符时,它会在输出列表的末尾创建一个空字符串?

如果您有多个空格分隔两个单词,则可能会发生这种情况。 例如,

'a    b'.split(' ') will return ['a', '', '', '', 'b']

但是我建议你使用 split from re 模块。检查下面的例子:

import re
print  re.split('[\s,; !]+', 'a b !!!!!!! ,     hello ;;;;; world')

当我们运行上面的片段时,它输出['a'、'b'、'hello'、'world']

docs:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.