How to print an integer with commas; E.g., 3,056,789

Max M maxm at mxm.dk
Wed Oct 16 09:42:47 EDT 2002


Richard Bow wrote:
> Given any integer n, how can I convert str(n) to a string with commas in 
> the appropriate places? For example, if n is 3056789, I'd like to convert 
> str(3056789) to "3,056,789", for better readability of output.

Try format in the locale module:

format(format, val[, grouping])

Formats a number val according to the current LC_NUMERIC setting. The 
format follows the conventions of the % operator. For floating point 
values, the decimal point is modified if appropriate. If grouping is 
true, also takes the grouping into account.

The "grouping" parameter is what you are looking for.

regards Max M




More information about the Python-list mailing list