将字符串拆分为一个列表,在python 3中使用相等长度的项目

时间:2015-04-11 06:05:52

标签: python

我正在寻找将一个给定的字符串拆分成一个长度相等的元素的列表,我发现一个代码段在python 3之前的版本中工作,这是我熟悉的唯一版本。

string = "abcdefghijklmnopqrstuvwx"
string = string.Split(0 - 3)
print(string)

>>> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"]

在python 3中运行时,它返回以下错误消息:

TypeError: Can't convert 'int' object to str implicitly

我可以进行哪些更改以使其与python 3兼容?

2 个答案:

答案 0 :(得分:0)

  1. 任何版本中的字符串没有属性Split
  2. 如果您打算撰写split,上述方法需要所有版本的
  3. 中的字符

    >>> string = "abcdefghijklmnopqrstuvwx"
    >>> string = string.split(0 - 3)
    Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
    TypeError: expected a character buffer object
    

    >>> 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
    

    那说......

    您可以使用以下代码拆分为相同的组:

    def split_even(item, split_num):
        return [item[i:i+split_num] for i in range(0, len(item), split_num)]
    

    因此:

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

答案 1 :(得分:0)

split_string_list = [string[x:x+4] for x in range(0,len(string),4)]

试试

基本上它是一个生成的列表,它从元素0-4开始,然后是4-8,等等,这正是你想要的,被类型化为字符串