gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:23:58 25 4
gpt4 key购买 nike

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

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', '']

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

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

最佳答案

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.

关于python - 使用默认分隔符与用户定义的分隔符拆分的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30271645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com