format() - Formats specified values in a string

The format method formats the specified values and inserts them inside the string's placeholder.  The format method requires comma delimited parameters specifying the placeholder name and the placeholder's value.


price = 49
txt = "Sale price: ${salePrice:.2f}! That's a {discount:.0%} savings!"
print(txt.format(salePrice = price, discount = .5))


Sale price: $49.00! That's a 50% savings!


Compare the formatting a string with the "f" prefix:


print(f'Sale price: ${price:.2f}! Savings: {.5:.0%}')


Sale price: $49.00! Savings: 50%

There are also several options for formatting placeholders:

  • :<    Left aligns the result
  • :>    Right aligns the result
  • :^    Centers the result
  • :=    Places the sign to the left-most position
  • :+    Use a plus sign to indicate if the result is positive or negative
  • :-    Use a minus sign or negative values only
  • :      Use a space to insert an extra space before positive numbers, and a minus sign before negative numbers
  • :,     Use a comma as a thousand's separator
  • :_    Use an underscore as a thousand's separator
  • :b    Binary format
  • :c    Converts the value into the corresponding Unicode character
  • :d    Decimal format
  • :e    Scientific notation with a lowercase e for the exponent
  • :E    Scientific notation with an uppercase E for the exponent
  • :f     Fix point number format
  • :F    Fix point number format and show "inf" (infinity) and "nan" (not a number) as INF and NAN
  • :g    General format
  • :o    Octal format
  • :x    Hex format, lowercase
  • :X    Hex format, uppercase
  • :n    Number format
  • :%    Percent format

Example regarding the + and - format options:

print('{a:+}, {b:+}, {a:-}, {b:-}'.format(a=1, b=-1))


+1, -1, 1, -1