Possible Duplicate:
How to print number with commas as thousands separators?
For example:
>> print numberFormat(1234)
>> 1,234
Or is there a built-in function in Python that does this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No one so far has mentioned the new
','option which was added in version 2.7 to the Format Specification Mini-Language — see PEP 378: Format Specifier for Thousands Separator in the What’s New in Python 2.7 document. It’s easy to use because you don’t have to mess around withlocale(but is limited for internationalization due to that, see the original PEP 378). It works with floats, ints, and decimals — and all the other formatting features provided for in the mini-language spec.Sample usage:
Note: While this new feature is definitely handy, it’s actually not all that much harder to use the
localemodule, as several others have suggested. The advantage is that then numeric output can be made to automatically follow the proper thousands (and other) separator conventions used in various countries when outputting things like numbers, dates, and times. It’s also very easy to put the default settings from your computer into effect without learning a bunch of language and country codes. All you need to do is:After doing that you can just use the generic
'n'type code for outputting numbers (both integer and float). Where I am, commas are used as the thousand separator, so after setting the locale as shown above, this is what would happen:Much of the rest of the world uses periods instead of commas for this purpose, so setting the default locale in many locations (or explicitly specifying the code for such a region in a
setlocale()call) produces the following:Output based on the
'd'or',d'formatting type specifier is unaffected by the use (or non-use) ofsetlocale(). However the'd'specifier is affected if you instead use thelocale.format()orlocale.format_string()functions.