how to use modulo (%) to wrap characters
Your data looks like this for a wrap of 4:
letter A B C D E F G H I J K L M N O ...
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
modulo 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 ...
mod(idx+1) 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 ...
So, you want to wrap when the modulo equals max_width-1
(here 3), or maybe easier to get, when modulo(index+1)
equals 0
:
def wrap(string, max_width):
result = ''
for i in range(len(string)):
result += string[i]
if (i+1) % max_width == 0:
result += '\n'
return result
print(wrap('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4))
output:
ABCD
EFGH
IJKL
MNOP
QRST
UVWX
YZ