format()
format(value[, format_spec]) Returns:
str · Added in v3.0 · Updated March 13, 2026 · Built-in Functions formatting strings built-in presentation
The format() built-in function converts a value to a formatted string using Python’s format spec mini-language. While often overshadowed by f-strings and str.format(), format() remains powerful for dynamic formatting scenarios and understanding how Python’s formatting system works under the hood.
Syntax
format(value, format_spec='')
- value: The object to format (numbers, strings, objects with
__format__) - format_spec: A string specifying how to format the value (optional)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
value | object | required | Any object with __format__ method support |
format_spec | str | '' | Format specification string |
Examples
Basic numeric formatting
# Integer formatting
format(42, 'd') # '42' - decimal
format(42, 'b') # '101010' - binary
format(42, 'o') # '52' - octal
format(42, 'x') # '2a' - hexadecimal (lowercase)
format(42, 'X') # '2A' - hexadecimal (uppercase)
Float precision and formatting
# Float precision
format(3.14159, '.2f') # '3.14' - 2 decimal places
format(3.14159, '.3f') # '3.142' - 3 decimal places
format(1.0, '.1f') # '1.0' - trailing zero preserved
# Scientific notation
format(1234.5, '.2e') # '1.23e+03'
format(1234.5, '.2E') # '1.23E+03'
String alignment and padding
# Left, right, center alignment
format('hello', '<10') # 'hello ' - left-aligned in 10 chars
format('hello', '>10') # ' hello' - right-aligned in 10 chars
format('hello', '^10') # ' hello ' - centered in 10 chars
# Numeric padding
format(42, '05d') # '00042' - zero-padded to 5 digits
format(42, '>10') # ' 42' - right-aligned
Thousands separator
# Comma separator for large numbers
format(1234567, ',') # '1,234,567'
format(1234567, ',.2f') # '1,234,567.00'
# Underscore separator (Python 3.6+)
format(1234567, '_') # '1_234_567'
Fill characters and alignment
# Custom fill character
format(42, '*<10') # '42********' - left with *
format(42, '*>10') # '********42' - right with *
format(42, '*^10') # '****42****' - centered with *
# Combined with numeric formatting
format(42, '*>+10') # '******+42' - right with sign
Comparison with other formatting methods
# format() vs f-strings vs str.format()
value = 42
precision = 2
# All produce the same result
format(value, f'.{precision}f') # '42.00'
f'{value:.{precision}f}' # '42.00'
'{0:.{1}f}'.format(value, precision) # '42.00'
# When format() shines: dynamic format_spec
def format_table(data, width):
return [format(item, f'^{width}') for item in data]
format_table(['Name', 'Age', 'City'], 10)
# [' Name ', ' Age ', ' City ']
Common Patterns
Currency formatting
def currency(value, symbol='$'):
return f'{symbol}{format(value, ",.2f")}'
currency(1234.56) # '$1,234.56'
currency(1000000) # '$1,000,000.00'
File size humanization
def human_size(bytes):
for unit in ['B', 'KB', 'MB', 'GB']:
if bytes < 1024:
return f'{format(bytes, ".1f")} {unit}'
bytes /= 1024
return f'{format(bytes, ".1f")} TB'
human_size(1500) # '1.5 KB'
human_size(1048576) # '1.0 MB'
Table column formatting
def format_row(values, widths):
return ' | '.join(format(v, f'^{w}') for v, w in zip(values, widths))
headers = ['Name', 'Score', 'Status']
row = ['Alice', 95, 'Pass']
print(format_row(headers, [10, 6, 8]))
# Name | Score | Status
# Alice | 95 | Pass
Errors
| Error | Cause |
|---|---|
ValueError | Invalid format_spec for the given type |
TypeError | Object doesn’t support formatting |
# Example of ValueError
format(3.14, 'd') # ValueError: Unknown format code 'd' for float
# Example of TypeError
format([1, 2, 3], 'd') # TypeError: unsupported format string passed to list