Published Sep 14, 2023Updated Oct 13, 2023
Contribute to Docs

The format() function returns a string from an input value, formatted to the provided specifications.


format(value, format_specification)

Where value is the value to format, and format_specification is the format specification to use.

Example format specifiers:

Specifier Meaning
b Binary format.
d Decimal format.
e Scientific format with lower case “e”.
E Scientific format with upper case “e”.
f Fixed-point format.
g General format.
x Hex format, lower case.
X Hex format, upper case.


In the following example, a float is formatted in a variable pi, which stores an approximation of the value of the constant pi. The format denotes that the output should be a string that represents the provided float, but only using two decimal places.

pi = 3.14159
formatted = format(pi, '.2f')

Output for above code is:


Codebyte Example

The codebyte example is runnable and uses the format() function to convert an integer to a binary and print its string representation.

Visit us
Hide code
Hide output
Hide output

All contributors

Looking to contribute?

Learn Python on Codecademy