-2

I've just finished a bit of code but realised once i start entering larger numbers everything began to seem a bit messy and un-organised. I decided i'd try to format the numbers from how python displays them to how you would write them in real life:

Example: 4567082 into 4,567,082 or 560867956 into 560,867,956, etc.

After trying this for a little while however, i came up with nothing. Just wondering as to what a solution for this may be if anyone knows.

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

-1
n1 = 4567082
n2 = 560867956
n3 = 120

def add_char(n, char):
    sn = str(n)
    rn = sn[::-1]
    return char.join(rn[s:s+3] for s in range(0, len(sn), 3))[::-1]

print(add_char(n1, ','))
print(add_char(n2, ','))
print(add_char(n3, ','))

Prints:

4,567,082
560,867,956
120
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91