You likely meant to do this:
message = [no_space[i:i+5] for i in range(0, len(no_space), 5)]
Think about what would happen in your code for a specific i
, say 90
. 90
is perfectly within the range because the range you specified was from 0
up to (but not including) len(no_space)
, which is 171
.
If i == 90
, then i + i+5 == 90 + 90+5 == 185
. You then request element 185
of no_space
with no_space[185]
. Since no_space
is only 171
characters long, you can't request element 185
, and so you get the IndexError
.
Hopefully this example will explain how this new code works, with a short string and splitting into 3's:
>>> s = 'abcdefghijk'
>>> len(s)
11
>>> list(range(0, len(s), 3))
[0, 3, 6, 9]
>>> s[0:3]
'abc'
>>> s[3:6]
'def'
>>> s[6:9]
'ghi'
>>> s[9:12]
'jk'
>>> [(i, i+3) for i in range(0, len(s), 3)]
[(0, 3), (3, 6), (6, 9), (9, 12)]
>>> [s[i:i+3] for i in range(0, len(s), 3)]
['abc', 'def', 'ghi', 'jk']