I have a string (without spaces) which I need to split into a list with items of equal length. I'm aware of the split()
method, but as far as I'm aware this only splits via spaces and not via length.
What I want to do is something like this:
string = "abcdefghijklmnopqrstuvwx"
string = string.Split(0 - 3)
print(string)
>>> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"]
I have thought about looping through the list but I was wondering if there was a simpler solution?
>>> [string[start:start+4] for start in range(0, len(string), 4)]
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx']
It works even if the last piece has less than 4 characters.
PS: in Python 2, xrange()
should be used instead of range()
.
How about :
>>> string = 'abcdefghijklmnopqrstuvwx'
>>> map(''.join, zip(*[iter(string)]*4))
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx']
>>>
or:
map(lambda i: string[i:i+4], xrange(0, len(string), 4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With