How would I be able to take a string like \'aaaaaaaaaaaaaaaaaaaaaaa\'
and split it into 4 length tuples like (aaaa
,aaaa
,aaaa
Here's another possible solution to the given problem:
def split_by_length(text, width):
width = max(1, width)
chunk = ""
for v in text:
chunk += v
if len(chunk) == width:
yield chunk
chunk = ""
if chunk:
yield chunk
if __name__ == '__main__':
x = "123456789"
for i in range(20):
print(i, list(split_by_length(x, i)))
Output:
0 ['1', '2', '3', '4', '5', '6', '7', '8', '9']
1 ['1', '2', '3', '4', '5', '6', '7', '8', '9']
2 ['12', '34', '56', '78', '9']
3 ['123', '456', '789']
4 ['1234', '5678', '9']
5 ['12345', '6789']
6 ['123456', '789']
7 ['1234567', '89']
8 ['12345678', '9']
9 ['123456789']
10 ['123456789']
11 ['123456789']
12 ['123456789']
13 ['123456789']
14 ['123456789']
15 ['123456789']
16 ['123456789']
17 ['123456789']
18 ['123456789']
19 ['123456789']
Using list comprehension, generator expression:
>>> s = 'aaaaaaaaaaaaaaaaaaaaaaa'
>>> [s[i:i+4] for i in range(0, len(s), 4)]
['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa']
>>> tuple(s[i:i+4] for i in range(0, len(s), 4))
('aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa')
>>> s = 'a bcdefghi j'
>>> tuple(s[i:i+4] for i in range(0, len(s), 4))
('a bc', 'defg', 'hi j')