0

Hey guy i recently found out this how you add commas between integer values, i have been trying to find out how it works i tried looking at other sources but none of them explain how this works?

Example: numbers = "{:,}".format(5000000) print(numbers)

I am wondering the logic behind {:,}

THE GM
  • 25
  • 6
  • https://stackoverflow.com/questions/1823058/how-to-print-a-number-using-commas-as-thousands-separators – Adid Jul 03 '22 at 07:12
  • 2
    can you share an example ? because comma could mean a very different thing depending on context – azro Jul 03 '22 at 07:12
  • 1
    Are you asking how it is implemented, or how to use it, or why it appears not to work for you? In the last case, show us the code. And it is called a *format specifier*, not a *function,* which has a specific meaning in programming languages. – BoarGules Jul 03 '22 at 07:37

2 Answers2

2
def add_comma(number: int) -> str:
    new_number, cnt = '', 0
    for num in str(number)[::-1]:
        if cnt == 3:
            new_number += ','
            cnt = 0

        new_number += num
        cnt += 1
    return new_number[::-1]

add_comma(1200000)
'1,200,000'

The mechanics behind it is that after every 3 numbers counting from behind, you add a comma to it; you start counting from behind and not from the beginning. So the code above is the equivalent of what the f-string function does for you.

For example, let's say the number '14589012'. To add comma to this, we count the first 3 numbers till we reach the beginning of the number, starting counting from the last digit in the number:

210,
210,985,
210,985,41

Then reverse the string, we have 14,589,012

I hope it helps, just read the code and explanation slowly.

0

{:,} is used along with format().

Example:

num = "{:,}".format(1000)
print(num)

Output: 1,000

This command add commas in every thousand place.

Example:

num = "{:,}".format(100000000)
print(num)

Output: 100,000,000