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

OhM*_*osh 7 python split

我尝试了一个字符串拆分的简单示例,但得到一些意想不到的行为.以下是示例代码:

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', '']
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,当我使用space作为split()函数的分隔符参数时,我在列表的末尾有一个额外的空字符串.但是,如果我没有传入split()函数的任何参数,我在输出列表的末尾没有空字符串.

从我在python docs中读到的内容,他们说split()的默认参数是space.那么,为什么当我明确地传入''作为分隔符时,它会在输出列表的末尾创建一个空字符串?

per*_*eal 15

文档:

如果未指定sep或为None,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,如果字符串具有前导或尾随空格,则结果在开头或结尾不包含空字符串.