str.split() 的拆分顺序是否有任何保证? [英] Are there any guarantees about the splitting order of str.split()?
问题描述
根据 Python 2.7 文档,使用 str.split()
指定了 maxsplit
将把字符串分割为 maxsplit
次.
According to the Python 2.7 docs, using str.split()
with maxsplit
specified will split a string up to maxsplit
times.
然而,它从未明确指定这些拆分将从左到右执行.有一个相关的函数 str.rsplit()
保证从右到左拆分排序.
However, it never explicitly specifies that these splits will be executed left to right. There is a related function str.rsplit()
that guarantees right to left split ordering.
除了在str.rsplit()
后面做字符串反转,有没有办法保证从左到右的拆分顺序?是否存在 str.split()
不会使用从左到右的顺序的情况?
Aside from doing string reverse followed by str.rsplit()
, is there any way to guarantee a left to right splitting order? Are there any situations where str.split()
will NOT use a left to right order?
推荐答案
如果您正在寻找使用 maxsplit
参数从左到右拆分的保证,您只需要查看在内置 python 测试套件.
If you're looking for guarantees that splitting with the maxsplit
argument splits from left-to-right, you only need to look at the builtin python test suite.
这里是摘录:
self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
sys.maxsize-2)
self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
self.checkequal(['abcd'], 'abcd', 'split', '|')
self.checkequal([''], '', 'split', '|')
self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
从测试中可以明显看出,任何执行不同操作的实现都会无法通过这些测试.
From the tests, it is clear that any implementation that did something different would fail these tests.
这篇关于str.split() 的拆分顺序是否有任何保证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!