'How to split string with number without spaces in Python, but 2 digits, 3 digits?

I have a string with numbers, I can split to individual numbers like

mynum = '123456'.replace(".", "")
[int(i) for i in mynum]
Output:
[1, 2, 3, 4, 5, 6]

I need to split to 2 digits like

[12, 34, 56]

also 3 digits

[123, 456]


Solution 1:[1]

One clean approach would use the remainder:

inp = 123456
nums = []
while inp > 0:
     nums.insert(0, inp % 100)
     inp /= 100

print(nums)  # [12, 34, 56]

The above can be easily modified e.g. to use groups of three numbers, instead of two.

Solution 2:[2]

For two-digit splitting:

[int(mynum[i:i+2]) for i in range(0,len(mynum),2)]

For three-digit splitting:

[int(mynum[i:i+3]) for i in range(0,len(mynum),3)]

So for n-digit splitting:

[int(mynum[i:i+n]) for i in range(0,len(mynum),n)]

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