-4

I want to write a program to split an integer's digits into groups of n digits, assuming that the number of digits is divisible by n.

For example, say I had the integer 123456789, and n=3, this would produce the list:

[123, 456, 789]

Or if the number was 12345678, and n=2, I would want the list:

[12, 34, 56, 78]

So the order of the digits remains the same. It is okay if the numbers in the list are strings, as this is easy to change.

EDIT: I apologise it seems that this question has already been asked. I shall look there for answers. Thank you to those who answered.

Motmot
  • 121
  • 1
  • 5

1 Answers1

2

I think you can create a generator function

def split_by_n( seq, n ):
    """A generator to divide a sequence into chunks of n units."""
    seq = str(seq)
    while seq:
        yield int(seq[:n])
        seq = seq[n:]

>>>list(split_by_n(1234567890,2))
[12, 34, 56, 78, 90]
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49