我尝试了一个字符串拆分的简单示例,但得到一些意想不到的行为.以下是示例代码:
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.那么,为什么当我明确地传入''作为分隔符时,它会在输出列表的末尾创建一个空字符串?