-3

I'm looking to split a given string into a list with elements of equal length, I have found a code segment that works in versions earlier than python 3 which is the only version I am familiar with.

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

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

When run in python 3 it returns the following error message:

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

What changes can I make to make this compatible with python 3?

Frank
  • 1
  • 3

2 Answers2

0
  1. There is no attribute Split for strings in any version of .
  2. If you intended to write split, the aforementioned method requires a character in all versions of

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

That said...

You can use the following code to split into equal groups:

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

As such:

>>> 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']
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
0
split_string_list = [string[x:x+4] for x in range(0,len(string),4)]

Try that

Basically what it is a list generated such that it starts with elements 0-4, then 4-8, etc. which is exactly what you want, typecasted into a string

itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
ubadub
  • 3,571
  • 21
  • 32
  • @ubadub Please dont say like this :( . Actually i forgotted what i edited. I think you have the privilage to accept/deny my edit? – itzMEonTV Apr 12 '15 at 09:01
  • @itzmeontv it's fine, you're right that it could be formatted better, it just seems kinda nitpickey. Forget it, I overreacted – ubadub Apr 14 '15 at 06:14