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

How to add a comma after every three integers in Python 3.10.4?

Add a character in between a string

How can I add a comma after every three characters in a string? For example, i have a string number = "2000", and the program should add a comma to the string after three places from the right. How can this be done?
I’ve tried this, but to no avail.

integer = 2000
print(str(integer)[:3] + "," + str(integer)[3:])

When i run this, it prints out 200,0

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

>Solution :

There are different ways to skin this cat, but the first one that suggests itself to me is to take the mod and div of the string length into 3, and use the mod (if any) to determine the length of the first segment before everything gets sliced evenly into threes:

>>> def three_commas(x):
...     a = len(x) % 3
...     b = len(x) // 3
...     return ",".join(([x[:a]] if a else []) + [x[a+3*i:a+3*i+3] for i in range(b)])
...
>>> three_commas("2000")
'2,000'
>>> three_commas("31415")
'31,415'
>>> three_commas("123456789")
'123,456,789'
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