ScanSkill

format

This format() function returns formatted strings in the specified format.

Syntax

format(value[, format])

Here,

  • value: Required. A value of any format, which needs to be formatted.
  • format: Optional. The format you want to format the value into. If omitted returns a string representation of the value.General form is:[[fill]align][sign][#][0][width][,][.precision][type] List of formatting specifiers:
    • fill (Any Characters)
    • align
      • '<' → Left aligns the result (within the available space)
      • '>' → Right aligns the result (within the available space)
      • '^' → Center aligns the result (within the available space)
      • '=' → Places the sign in the left-most position
    • sign
      • '+' → Use a plus sign to indicate if the result is positive or negative
      • '-' → Use a minus sign for negative values only
      • ' ' → Use a leading space for positive numbers
      • ',' → Use a comma as a thousand separator
      • '_' → Use an underscore as a thousand separator
    • width (Integer)
    • precision (integer)
    • type
      • 'b' → Binary format
      • 'c' → Converts the value into the corresponding Unicode character
      • 'd' → Decimal format
      • 'e' → Scientific format, with a lower case e
      • 'E' → Scientific format, with an upper case E
      • 'f' → Fix point number format
      • 'F' → Fix point number format, upper case
      • 'g' → General format
      • 'G' → General format (using an upper case E for scientific notations)
      • 'o' → Octal format
      • 'x' → Hex format, lower case
      • 'X' → Hex format, upper case
      • 'n' → Number format
      • '%' → Percentage format

Examples

  • With sign options
>>> format(13, '-')
'13'
>>> format(13, '+')
'+13'
>>> format(13, ' ')
' 13'
>>> format(-13, ' ')
'-13'
>>> format(-13, '+')
'-13'
  • With fill, align, and width ([fill][align][width])
>>> format(1.32, '0>10')
'0000001.32'
>>> format(1.32, '0<10')
'1.32000000'
>>> format(1.32, '0=10')
'0000001.32'
>>> format(1.32, '0^10')
'0001.32000'
>>> format(1.32, '#<10')
'1.32######'
>>> format(1.32, '#^10')
'###1.32###'
  • With [,] option
>>> format(123456789, ',')
'123,456,789'
  • With [precision] option
>>> format(13.256, '.2f')
'13.26'
>>> format(13.256, '.3f')
'13.256'
>>> format(13.256, '.1f')
'13.3'
>>> format(13.256, '.0f')
'13'
  • With [type] option on integers and floats
>>> format(2, 'c')
'\\x02'
>>> format(2, 'd')
'2'
>>> format(100, 'o')
'144'
>>> format(100, 'x')
'64'

>>> format(3.13592, 'E')
'3.135920E+00'
>>> format(3.13592, 'f')
'3.135920'
>>> format(3.13592, 'g')
'3.13592'
>>> format(3.13592, '.2g')
'3.1'
>>> format(3.13592, '%') # Try this at home :-)