Sometimes, we want to print number with commas as thousands separators with Python.
In this article, we’ll look at how to print number with commas as thousands separators with Python.
How to print number with commas as thousands separators with Python?
To print number with commas as thousands separators with Python, we can use the {:n}
format code.
For instance, we write:
import locale
locale.setlocale(locale.LC_ALL, '')
value = 10000000
curr_1 = '{:n}'.format(value)
curr_2 = f'{value:n}'
print(curr_1)
print(curr_2)
to call locale.setlocale
to set the locale.
Then we have the value
that we want to format into a comma separated number.
Next, we call format
with value
to format the number into a comma separated number by using '{:n}'
as the placeholder.
And we do the same with the f-string by passing in value
before the colon.
Therefore, curr_1
and curr_2
are both 10,000,000.
Conclusion
To print number with commas as thousands separators with Python, we can use the {:n}
format code.