1

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]
hanzgs
  • 1,498
  • 17
  • 44

2 Answers2

2

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

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)]
hashim
  • 55
  • 7
  • You should probably give a quick explanation into why that works ! Note also that your bounds in your first range are probably wrong (you are missing the initial 0 if you want to give a step with no kwargs !). Finally, I honestly don't get why you don't just split the string int(mynum[i:i+2]), and have to ressort to base 10 calculations. Answer can be improved ! – Manuel Faysse May 17 '22 at 09:09
  • 1
    @ManuelFaysse Thanks for pointing out the mistakes. The answer is now edited. – hashim May 18 '22 at 04:06