'How Can I Split string every nth character, And Display like This?

I want to print the following string:

1234567890

as follows:

123
456
789
0

How can I do this in Python?



Solution 1:[1]

You could use re.findall here:

inp = '1234567890'
output = '\n'.join(re.findall(r'.{1,3}', inp))
print(output)

This prints:

123
456
789
0

Solution 2:[2]

try this:

x = "1234567890"
n = 3

y = list([x[i:i+n] for i in range(0, len(x), n)])

for chunk in y:
    print(chunk)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Biegeleisen
Solution 2 Orius