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

>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'

Leave a Reply