Can anyone help me with this problem?
python - Add commas into number string - Stack Overflow
string - How to format a number with comma every four digits in Python? - Stack Overflow
python - How to print a number using commas as thousands separators - Stack Overflow
Videos
Let's say I have 2792819, now I want it to be like 2,792,819. How do I do it?
I can do so while reversing it and after every 3 iterations, put a comma or something like that. But is there a better way to do so?
In Python 2.7 and 3.x, you can use the format syntax :,
>>> total_amount = 10000
>>> print("{:,}".format(total_amount))
10,000
>>> print("Total cost is: ${:,.2f}".format(total_amount))
Total cost is: $10,000.00
This is documented in PEP 378 -- Format Specifier for Thousands Separator and has an example in the Official Docs "Using the comma as a thousands separator"
if you are using Python 3 or above, here is an easier way to insert a comma:
First way
value = -12345672
print (format (value, ',d'))
or another way
value = -12345672
print ('{:,}'.format(value))
Regex will work for you:
import re
def format_number(n):
return re.sub(r"(\d)(?=(\d{4})+(?!\d))", r"\1,", str(n))
>>> format_number(123)
'123'
>>> format_number(12345)
'1,2345'
>>> format_number(12345678)
'1234,5678'
>>> format_number(123456789)
'1,2345,6789'
Explanation:
Match:
(\d)Match a digit...(?=(\d{4})+(?!\d))...that is followed by one or more groups of exactly 4 digits.
Replace:
\1,Replace the matched digit with itself and a,
Sounds like a locale thing(*). This prints 12,3456,7890 (Try it online!):
import locale
n = 1234567890
locale._override_localeconv["thousands_sep"] = ","
locale._override_localeconv["grouping"] = [4, 0]
print(locale.format_string('%d', n, grouping=True))
That's an I guess hackish way based on this answer. The other answer there talks about using babel, maybe that's a clean way to achieve it.
(*) Quick googling found this talking about Chinese grouping four digits, and OP's name seems somewhat Chinese, so...
Locale-agnostic: use _ as the thousand separator
f'{value:_}' # For Python ≥3.6
Note that this will NOT format in the user's current locale and will always use _ as the thousand separator, so for example:
1234567 ⟶ 1_234_567
English style: use , as the thousand separator
'{:,}'.format(value) # For Python ≥2.7
f'{value:,}' # For Python ≥3.6
Locale-aware
import locale
locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'
'{:n}'.format(value) # For Python ≥2.7
f'{value:n}' # For Python ≥3.6
Reference
Per Format Specification Mini-Language,
The
','option signals the use of a comma for a thousands separator. For a locale aware separator, use the'n'integer presentation type instead.
and:
The
'_'option signals the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type'd'. For integer presentation types'b','o','x', and'X', underscores will be inserted every 4 digits.
I'm surprised that no one has mentioned that you can do this with f-strings in Python 3.6+ as easy as this:
>>> num = 10000000
>>> print(f"{num:,}")
10,000,000
... where the part after the colon is the format specifier. The comma is the separator character you want, so f"{num:_}" uses underscores instead of a comma. Only "," and "_" is possible to use with this method.
This is equivalent of using format(num, ",") for older versions of python 3.
This might look like magic when you see it the first time, but it's not. It's just part of the language, and something that's commonly needed enough to have a shortcut available. To read more about it, have a look at the group subcomponent.
Your own example is able to do what you want. Just write it properly without mixing format styles:
a = 1234567
print "The number is {:,d} but it's converted to a string".format(a)
That's a good reason to use the modern syntax. It does not care about the type of the argument. It will use str on the object and output it accordingly.
print "The number is {:,d} and John has {} sisters and {} brothers".format(1000000, 2, 3)
To be clear, a itself is not being changed into a string. There is a temporary, anonymous string object created by '{:,d}'.format(a) and then fed to "%s" %:
>>> a = 1234567
>>> "The number is %s but it's converted to a string" %'{:,d}'.format(a)
"The number is 1,234,567 but it's converted to a string"
>>> type(a)
<type 'int'>
>>> a
1234567
So a itself has not changed at all similarly as your second example does not change the object b:
>>> b = 0.1234
>>> "The Norwegian Blue prefers kippin' on it's back! %0.2f%%" % (b*100)
"The Norwegian Blue prefers kippin' on it's back! 12.34%"
>>> type(b)
<type 'float'>
>>> b
0.1234
So the underlying values of a and b are not changing. The issue is that you are using a less than clear syntax to print a. Just do:
>>> "The number is {:,d} but it's NOT converted to a string".format(a)
"The number is 1,234,567 but it's NOT converted to a string"
There is no need to do two formatting steps as you have in your example.