gpt4 book ai didi

python - 为什么 re.split() 在结果列表的末尾返回一个额外的空白?

转载 作者:行者123 更新时间:2023-11-28 16:38:35 25 4
gpt4 key购买 nike

print re.split("([0-9]{4})", "Spring2014")

结果

['Spring', '2014', '']

最后那个额外的''来自哪里?我想要的列表是上面的,最后没有那个额外的空白项目。丢弃多余的项目很容易,但我只是想了解为什么 re.split 包含它。

最佳答案

您要求 re.split() 将文本拆分为 4 位数字部分;字符串 before '2014' 包含 'Spring',在那部分之后是字符串 ''.

这是 documented behaviour :

If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for the end of the string:

>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']

That way, separator components are always found at the same relative indices within the result list (e.g., if there’s one capturing group in the separator, the 0th, the 2nd and so forth).

关于python - 为什么 re.split() 在结果列表的末尾返回一个额外的空白?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22721482/

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