Sunday 15 September 2013

python - How to print number with commas as thousands separators? -


I'm trying to print an integer in Python 2.6.1 , because thousands For algebraic commas, for example, I want to show as 1234567 as 1,234,567 . How would I go about doing this? I've seen many examples on Google, but I'm looking for the simplest practical way.

It does not need to be location-specific to decide between period and comma. I would prefer something as simple as possible.

I found it to work:

<> & gt; & Gt; & Gt; Import locale & gt; & Gt; & Gt; Locale.setlocale (locale.LC_ALL, 'en_US') 'en_US' & gt; & Gt; & Gt; Locale The format ("% d", 1255000, grouping = true) '1,255,000'

Of course, you do not support internationalization, but it is clear, concise, and Uses an underlying library.

PS This "% d" is the normal% -style format you can have only one formatter, but whatever you can do in terms of this field width and exact setting.

P.P.S. If you can not find the locale to work, I suggest a revised version of the answer to Mark:

  def intWithCommas (x): if type ( X) Not in [Type (0), Type (0L)]: Increase type error ("Parameter should be an integer.") If x & lt; 0: returns '-' + intWithCommas (-x) result = '' while x & gt; = 1000: x, r = divmod (x, 1000) result = ",% 03d% s"% (r, result) return "% D% s"% (x, result)  
< P> Useful for recursive negative case, but according to each comma a recurrence takes me a little more.


No comments:

Post a Comment