In python, is there an easy way to turn comma numbers into an integer and then back into comma numbers?

Let's say I have a number like this:

8 741 or 8 741 291

How can I use python to multiply this number by 2 and then insert commas in it? I want the python function to return

17.482 and 17.482.582 , in string format.

+4
source share
2 answers
my_str = '1,255,000' my_num = int(my_str.replace(',','')) #replace commas with nothing 

this will return my_num = 1255000

 result = my_num * 2 import locale locale.setlocale(locale.LC_ALL, 'en_US') my_str = locale.format("%d", result, grouping=True) 

this will return-> my_str = '2,510,000'

+11
source

The first part is simple:

 temp = "8,741,291".replace(',', '') n = int(temp) * 2 

I thought returning commas was a bit more difficult, but it really is not!

If you are using the latest version of Python, you can use the new .format() line method as follows:

 s = "{0:,}".format(n) 

If you are using Python later than 2.6, you can omit 0 from the curly braces in this example. (Alas, I have to use Cygwin, and, alas, it only gives 2.6, so I use 0 for input.)

The specification mini-language for the .format() method is here:

http://docs.python.org/library/string.html#formatstrings

@ user1474424 explained the function locale.format() , which is cool; I did not know about it. I checked the documents; It has been around since Python 1.5!

http://docs.python.org/library/locale.html

+6
source

All Articles