Home Python Built-in Functions format() Definition In Python, format(value, spec) converts one value to text using a format spec such as ".2f" (two decimals), "," (thousands separator), or ">8" (right-align in 8 characters). With no spec it behaves like str() .
The spec is the same mini-language used after the colon in f-strings and str.format() : format(x, ".2f") equals f"{x:.2f}". Each type decides what its spec means through __format__(), which is why dates accept codes like %Y.
format() is a built-in function : it lives in the builtins module, so it is always available without an import.
Syntax Pass the value and a spec string.
text = format(value, format_spec)
# [[fill]align][sign][#][0][width][,][.precision][type] Call What it does format(3.14159, ".2f")Returns "3.14". format(1234567, ",")Returns "1,234,567". format(0.256, ".1%")Returns "25.6%". format("hi", "*^6")Returns "**hi**": centered with a fill character.
Align with < (left), > (right), or ^ (center); numbers align right and text aligns left by default.
Library declarations format(value, format_spec="", /)
# calls type(value).__format__(value, format_spec) Parameters Parameter Description value Required. The value to format. format_spec Optional. A format spec string. Default "", which gives the same result as str(value) for most types.
Return Value Return Value Description str The formatted text.
Important
A spec that does not fit the type raises ValueError, for example format("abc", ".2f") or format(3.5, "d"). Formatting with f rounds the displayed value only; the number itself is unchanged.
Python Examples 1. Number specs 2. Align a table 3. Dates and __format__ Example 1 — Decimals, Separators, Percent, and Bases Format six numbers with the most common spec codes.
pi = 3.14159265
print(format(pi, ".2f"))
print(format(1234567.891, ",.2f"))
print(format(0.256, ".1%"))
print(format(42, "05d"))
print(format(255, "x"), format(255, "#b"))
print(format(1500000, ".2e")) 3.14
1,234,567.89
25.6%
00042
ff 0b11111111
1.50e+06 How It Works Fixed decimals. .2f rounds to two places: 3.14.Thousands separator. ,.2f adds commas and keeps two decimals.Percent. .1% multiplies by 100 and adds a percent sign with one decimal.Zero padding, bases, exponent. 05d pads to five digits, x and #b switch base, and .2e uses scientific notation.Example 2 — Line Up a Price Table Use widths and alignment to print columns that line up, then center a footer with a fill character.
rows = [("Apple", 1.5, 3), ("Banana", 0.25, 12), ("Cherry", 10.0, 1)]
print(format("Item", "<8") + format("Price", ">7") + format("Qty", ">5"))
for name, price, qty in rows:
print(format(name, "<8") + format(price, ">7.2f") + format(qty, ">5d"))
print(format("end", "*^20")) Item Price Qty
Apple 1.50 3
Banana 0.25 12
Cherry 10.00 1
********end********* How It Works Fixed widths. Every column has a width (8, 7, 5), so each line has the same length.Text left, numbers right. <8 left-aligns names and >7.2f right-aligns prices with two decimals.Same spec per column. The header uses the same widths as the rows, so the titles sit above their values.Fill and center. *^20 centers "end" in 20 characters padded with stars.Example 3 — Format Dates and Your Own Classes See how a type defines its own spec language: date uses strftime codes, and a custom class adds a "usd" spec.
from datetime import date
class Money:
def __init__(self, amount):
self.amount = amount
def __format__(self, spec):
if spec == "usd":
return "USD " + format(self.amount, ",.2f")
return format(self.amount, spec)
day = date(2024, 3, 9)
print(format(day, "%Y-%m-%d"))
print(format(day, "%d %b %Y"))
print(f"{day:%A}")
price = Money(1234.5)
print(format(price, "usd"))
print(f"{price:.1f}") 2024-03-09
09 Mar 2024
Saturday
USD 1,234.50
1234.5 How It Works Type-specific specs. date.__format__ treats the spec as strftime codes, so %Y-%m-%d gives an ISO date.Same in f-strings. f"{day:%A}" passes "%A" to the same method and prints the weekday.Your own spec. Money.__format__ recognises "usd" and adds a currency label and separators.Delegate the rest. Any other spec, like .1f, is passed on to the float's own formatting.Frequently Asked Questions How do I format a number to 2 decimal places in Python? Use format(x, ".2f") or f"{x:.2f}". Both return a string such as "3.14".
How do I add thousands separators? Use the comma option: format(1234567, ",") returns "1,234,567"; add .2f for decimals: format(x, ",.2f").
What is the difference between format() and str.format()? format(value, spec) formats one value. "...".format(a, b) fills placeholders in a template. Both use the same spec mini-language.
How do I pad a number with zeros? Use a zero and a width: format(7, "03d") returns "007". f"{7:03d}" does the same.
How does my class support format()? Define __format__(self, spec) and return a string. Delegate unknown specs to format() on an inner value.
Next: frozendict() Immutable, hashable mapping (new in Python 3.15).
frozendict() → About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
14 people found this page helpful
Helpful Share Copy link Suggestion