There is a kata in codewars where the task is to write a function that takes an integer in input and outputs a string with currency format. For example 123456
-> "123,456"
.
I had a solution, but it was much uglier than this one with string formatting:
def to_currency(price):
return '{:,}'.format(price)
I've read the documentation, but I still don't know how is this working exactly?
You can use python's format language like:
'{name:format}'.format(...)
name
is optional, and can be empty:
'{:format}'.format(...)
format
is a format specifier. If it's not given, it's usually inferred from the type of the argument given to format(...)
.
In this case, format
is ,
, which instructs python to add group dividers, like demanded.
From https://docs.python.org/2/library/string.html#formatspec :
The
,
option signals the use of a comma for a thousands separator. For a locale aware separator, use then
integer presentation type instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With