Python

Search for '{{search_term}}'

How to commafy a number? (How to print number with commas as thousands separators using Python?)

CMOS is the Code-Maven Open Source podcast that also includes video interviews. Subscribe to this feed RSS feed with your Podcast listener app or via iTunes iTunes.

examples/python/commafy.py

from __future__ import print_function

small = 42
big = 1234567

print(small)      # 42
print(big)        # 1234567

print("{:,}".format(small)) # 42
print("{:,}".format(big))   # 1,234,567

We have imported the print_function from the __future__ so this code will work on both Python 2 and Python 3.

The key here is the {:,} placeholder.

Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus