Split string into a list, with items of equal length in python 3
本问题已经有最佳答案,请猛点这里访问。
我想把一个给定的字符串分割成一个元素长度相等的列表,我发现了一个代码段,它可以在我熟悉的惟一版本python 3之前的版本中工作。
1 2 3 4 5 | string ="abcdefghijklmnopqrstuvwx" string = string.Split(0 - 3) print(string) >>> ["abcd","efgh","ijkl","mnop","qrst","uvwx"] |
在python 3中运行时,它返回以下错误消息:
1 | TypeError: Can't convert 'int' object to str implicitly |
为了使它与Python3兼容,我可以做什么更改?
1 | split_string_list = [string[x:x+4] for x in range(0,len(string),4)] |
试试那个
基本上,它是一个列表,它从元素0-4开始,然后是元素4-8,等等,这正是您想要的,类型化为一个字符串
Python 2.x
1 2 3 4 5 | >>> string ="abcdefghijklmnopqrstuvwx" >>> string = string.split(0 - 3) Traceback (most recent call last): File"<stdin>", line 2, in <module> TypeError: expected a character buffer object |
Python 3.x
1 2 3 4 5 | >>> string ="abcdefghijklmnopqrstuvwx" >>> string = string.split(0 - 3) Traceback (most recent call last): File"python", line 2, in <module> TypeError: Can't convert 'int' object to str implicitly |
说…
您可以使用以下代码分成相等的组:
1 2 | def split_even(item, split_num): return [item[i:i+split_num] for i in range(0, len(item), split_num)] |
像这样的:
1 2 3 4 5 6 7 | >>> split_even("abcdefghijklmnopqrstuvwxyz", 4) ['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx', 'yz'] >>> split_even("abcdefghijklmnopqrstuvwxyz", 6) ['abcdef', 'ghijkl', 'mnopqr', 'stuvwx', 'yz'] >>> split_even("abcdefghijklmnopqrstuvwxyz", 13) ['abcdefghijklm', 'nopqrstuvwxyz'] >>> |