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]
3
  • Assuming you want pairs of digits, what would the output be from 12345 ? Commented May 17, 2022 at 2:11
  • I always have even digits if I want to split for 2 digits Commented May 17, 2022 at 2:12
  • this might be useful link Commented May 17, 2022 at 2:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This has some useful solution as well
@hanzgs That looks like a potential duplicate...you may hammer if you wish.
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)]

2 Comments

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 !
@ManuelFaysse Thanks for pointing out the mistakes. The answer is now edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.