format()

format(value, format_spec="") -> str
Returns: str · Added in v3.0 · Updated April 3, 2026 · Built-in Functions
built-in formatting strings numbers

The format() builtin converts a value into a formatted string using a format specification mini-language. When you write f-strings like f"{x:>10}" or call "{}".format(x), Python delegates the actual formatting to format() under the hood.

Syntax

format(value, format_spec="")
ParameterTypeDefaultDescription
valueanyThe value to format. Can be a string, number, or any object implementing __format__().
format_specstr""The format specification string controlling how the value is presented.

Returns: A formatted string representation of the value.

Alignment and Fill

Use width to ensure a minimum character width, and alignment to control where the content sits within that space:

text = "Hi"

print(format(text, ">10"))   # right-aligned
print(format(text, "<10"))   # left-aligned
print(format(text, "^10"))   # centered
print(format(text, "->10"))  # right-aligned, dash-filled
print(format(text, "*^10"))  # centered, star-filled

# Output:
#         Hi
# Hi
#     Hi
# --------Hi
# ****Hi****

Alignment requires an explicit fill character when you want something other than a space. format(42, "x>10") means fill=x, align=>, width=10 → "xxxxxxxx42". But format(42, "x10") (no alignment) ignores the fill character and just produces " 42".

Numeric Types

The format specification mini-language includes type codes for different numeric representations:

x = 42

print(format(x, "b"))    # binary
print(format(x, "c"))   # character (Unicode)
print(format(x, "d"))   # decimal
print(format(x, "o"))   # octal
print(format(x, "x"))    # hex lowercase
print(format(x, "X"))    # hex uppercase
print(format(x, "08d"))  # zero-padded decimal

# Output:
# 101010
# *
# 42
# 52
# 2a
# 2A
# 00000042

Negative numbers with zero-padding place the sign first, then zero-fill:

print(format(-42, "010"))
# -000000042

Sign and Alternate Form

Control how signs and numeric prefixes appear:

n = -255
p = 255

print(format(n, "+d"))      # always show sign
print(format(p, "+d"))
print(format(n, " "))       # space for positive
print(format(p, " "))
print(format(255, "#x"))    # alternate form: 0x prefix
print(format(255, "#o"))    # alternate form: 0o prefix
print(format(255, "#b"))    # alternate form: 0b prefix

# Output:
# -255
# +255
# -255
#  255
# 0xff
# 0o377
# 0b11111111

Floating-Point Precision

The precision meaning depends on the type code. For f (fixed-point), precision means digits after the decimal point. For g (general), precision means total significant digits:

pi = 3.14159265

print(format(pi, "f"))      # fixed-point, default 6 decimals
print(format(pi, ".2f"))    # 2 digits after decimal
print(format(pi, ".3e"))    # scientific, 3 decimal places
print(format(pi, ".3g"))    # general, 3 significant digits
print(format(pi, "%"))      # percentage

# Output:
# 3.141593
# 3.14
# 3.142e+00
# 3.14
# 314.159265%

This distinction trips people up. format(2.345, ".2f") gives "2.35" (two decimal places), while format(2.345, ".2g") gives "2.3" (only two significant digits).

Grouping Options

Add thousands separators to large numbers:

print(format(1234567, ","))   # comma separator
print(format(1234567, "_"))   # underscore separator

# Output:
# 1,234,567
# 1_234_567

Custom Formatting with __format__

Any class can define __format__(self, format_spec) to control how format() formats it. Python calls this method when you pass a custom object to format():

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def __format__(self, spec):
        if spec == "":
            return f"{self.celsius}°C"
        elif spec == "F":
            return f"{self.celsius * 9/5 + 32}°F"
        elif spec == "K":
            return f"{self.celsius + 273.15}K"
        else:
            raise ValueError(f"Unknown format spec: {spec}")

t = Temperature(25)
print(format(t))       # default
print(format(t, "F"))  # Fahrenheit
print(format(t, "K"))  # Kelvin

# Output:
# 25°C
# 77.0°F
# 298.15K

The datetime module uses this same mechanism, which is why you can write f"{dt:%Y-%m-%d}" in an f-string.

Common Gotchas

Fill character requires alignment

format(42, "x10") (no alignment) treats x as a literal character in the spec, not a fill. You get " 42", not left-aligned 42s. You need format(42, "x<10") to fill with x.

String truncation with s type

For strings, .5s truncates to 5 characters, not 5 decimal places:

print(format("hello world", ".5s"))
# hello

n type uses locale-aware separators

On a US system, format(1234, "n") might return "1234". On a German system, it could return "1.234". The d and g types are always consistent across locales.

See Also

  • fstring-guide — f-strings use format() internally for their :spec portion
  • str::format — the string method, not the builtin described here
  • dunder-format__format__(), the dunder method custom types implement