format() Format a value
Last updated: 2026-09-22
format() Format a value
format(value, format_spec='') returns value formatted according to format_spec.
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
format(value[, format_spec])
⚙️ Parameters
| value Required | The value to format. |
|---|---|
| format_spec Optional | Format specifier, e.g. '.2f', '08b'.(Default:'') |
Returns:str. The value formatted according to format_spec.
💥 Raises
TypeError— Raised when format_spec is invalid or unsupported for the value's type.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
3.14
11111111
0xff
🏷️ Related Built-in Functions
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QIs format() the same syntax as the colon in f-strings?
AYes — f'{3.14159:.2f}' internally calls format(3.14159, '.2f'); the two are fully equivalent and interchangeable.
QWhat does format(5, '08b') return?
AIt returns '00000101': 'b' means binary, '8' means a width of 8 digits, and '0' means zero-pad on the left.
QWhat does format(255, '#x') return?
AIt returns '0xff'; the '#' flag makes hexadecimal include the 0x prefix, without it you get 'ff'. Likewise '#o' and '#b' add the 0o and 0b prefixes.
QWhat happens when the format specifier is wrong?
AIt raises a ValueError or TypeError (e.g. format(1.5, 'abc')) — the specifier syntax and per-type support are strictly validated.