.format()
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.
Syntax
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. |
Example
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.14159formatted = format(pi, '.2f')print(formatted)
Output for above code is:
3.14
Codebyte Example
The codebyte example is runnable and uses the format()
function to convert an integer to a binary and print its string representation.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours