Python: '{:,}'. Format () Why does it work?

There is a kata in code guides, where the task is to write a function that takes an integer in the input and displays a string with a currency format. For example 123456"123,456".

I had a solution, but it was much uglier than this with string formatting:

def to_currency(price):
  return '{:,}'.format(price)

I read the documentation, but I still don't know how it works exactly?

+4
source share
3 answers

You can use python format language, for example:

'{name:format}'.format(...)

name is optional and may be empty:

'{:format}'.format(...)

format- format specifier. If it is not specified, it is usually inferred from the type of the argument specified format(...).

format ,, python , . https://docs.python.org/2/library/string.html#formatspec:

, . n integer .

+8

, : , :

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]

',' . , , n 'integer.

+6

:

:

>>>
>>> '{:,}'.format(1234567890)
'1,234,567,890'

: .

The format specifier ,signals the use of a comma for the thousands separator. It was added in versions 2.4 and 3.1 in Python and is described in more detail in PEP 0378 .

0
source

Source: https://habr.com/ru/post/1588969/


All Articles