Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: '{:,}'.format() why is this working?

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?

like image 959
Kat Avatar asked Dec 09 '22 03:12

Kat


1 Answers

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 the n integer presentation type instead.

like image 69
Marcus Müller Avatar answered Dec 28 '22 20:12

Marcus Müller