Python format() Function


Python format() is a built-in function that returns the formatted representation of the given value. So simply it returns a formatted string.

python format() function

Python format() Syntax

format(value[,format_spec])

format() method takes two parameters.

  • value (optional) – a value or a type to be formatted.
  • format_spec (optional) – It determines how the value is to be formatted. If omitted, it returns the string representation of the object.

The general format of format_spec is

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

Where,

fill

fill can be any character.

align

Align represents the symbols used to manage the adjustments in positions.

  • < : Forces the field to be left aligned.
  • > :Forces the field to be right aligned.
  • = : Valid for numeric data only. Forces padding to be placed between digit and the sign (eg. -00034).
  • ^ : Forces the field to be centered.

Sign

  • + : used for both positive and negative numbers.
  • - : used for negative numbers only.
  • space ( '  ' )  : leading space used on positive numbers.
  • # : valid only for integers, binary, octal and hexadecimal numbers. It specifies that the output will be prefixed by ‘0b‘ (binary), ‘0x‘(hex), ‘0o‘(octal).
  • , ‘ (comma) : thousands operator that places ‘ , ‘ (comma)  between all thousands.

Width

Width is a number that defines the minimum field width.

Precision

Indicates the number of digits to be displayed after the decimal point.

Type

It determines how data is displayed.

It can have following values.

"b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

For example, ‘c’ signifies character type representation.

How does Python format() work?

Well when we call format() function, it automatically invokes __format__() method associated with the object.

For example, when we call format(obj, format_spec) , what in actual is happening that the format() function is invoking __format__() method associated with the object obj i.e. obj.__format__(format_spec).

Now, let’s look at some examples.

Python format() function example

>>> #using fill,align and width
>>> format(11.11, 0>8)
'00011.11''
>>> format(11.11, #>8)
'###11.11'

>>> #using # option..only for binary,ocatal,hex and integers
>>> format(5,'0b')
'0101'
>>> format(10,'0x')
'a'

>>> #using sign
>>> format('5','+')
5
>>> format('-5',' ') #no effect on negative numbers
-5
>>> format(5, ' ')  #leading space for postive numbers
' 5'

>>> #using [,]
>>> format(12121212, ',')
'12,121,212'

>>> #using precision
>>> format(3.14141414, '.2f')
3.14
>>> format(3.14141414, '.5f')
3.14141

>>> #using [type]
>>> format(5, 'b')
'101'
>>> format(5, 'c')
'\x05'
>>> format(2, 'd')
'2'
>>> format(5, 'e')
'5.000000e+00'