1

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

3 Answers3

2

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):
...     b, a = divmod(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'
Samwise
  • 68,105
  • 3
  • 30
  • 44
1

this is a little easy to understand solution.

first we reverse the number then insert , every 3 places then we reverse the number again.

def formatNum(integer):
    temp = str(integer)[::-1]
    k=0
    str1=""
    for i in temp:
        if(k==3):
            str1 = str1+ ','+i
            k=0
        else:
            str1 = str1+i
        k=k+1
    return str1[::-1]

integer = 2000
print(formatNum(integer))
Abrar Malek
  • 231
  • 1
  • 5
1

Using a regex, you can match 3 digits and assert a digit to the left and and check if there are optional repetitions of 3 digits to the right.

Then replace with a comma and the full match ,\g<0>

(?m)(?<=\d)\d{3}(?=(?:\d{3})*$)

The pattern matches:

  • (?m) Enable multiline
  • (?<=\d) Positive lookbehind, assert a digit to the left
  • \d{3} Match 3 digits
  • (?= Positive lookahead
    • (?:\d{3})*$ Optionally match 3 digits till the end of string
  • ) Close looakhead

Example

import re

pattern = r"(?m)(?<=\d)\d{3}(?=(?:\d{3})*$)"
s = "2000\n31415\n123456789"

print(re.sub(pattern, r",\g<0>", s))

Output

2,000
31,415
123,456,789
The fourth bird
  • 154,723
  • 16
  • 55
  • 70