Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split number into groups by magnitude

given an input 34567890

I want an output: [34, 567, 890]

I can do it with some modulo math and floor division

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

num=34567890
output_list = []
division_tracker = num
while division_tracker > 0:
    output_list.insert(0, division_tracker%1000)
    division_tracker = division_tracker//1000

Is there a better way?

>Solution :

This is kind of hacky, but:

>>> list(map(int, f'{34567890:,}'.split(',')))
[34, 567, 890]

f'{n:,}' generates a string of the integer n with commas as thousands separators, we split the resulting string at comma and cast the parts into int.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading