format() Built-in Function


Python - format()

Python format() built-in function is used to format a given value into a specified representation.

In this tutorial, we will learn the syntax and usage of format() built-in function, how to use this function to format values into a specific representation, with the help of example programs.

Syntax

The syntax of format() function is

format(value, format_spec='')

where

ParameterDescription
valueAny value.
format_specThe format specification that effects the representation of the given value.

Please refer Format Specification for different values that format_spec parameter can take, and how they effect the representation of value.

Examples

1. Format number with comma as thousand separator

In the following program, we take an integer value, and format this value with comma as a thousand separator.

Python Program

n = 123456789
output = format(n, ',')
print(output)

Output

123,456,789

2. Format decimal to scientific notation

In the following program, we take a decimal value, and format this value to scientific notation.

Python Program

n = 0.00123456789
output = format(n, 'E')
print(output)

Output

1.234568E-03

3. Format decimal to percentage

In the following program, we take a decimal value, and format this value to percentage notation. The decimal value is converted to percentage, and % symbol is appended to the value.

Python Program

n = 0.1234
output = format(n, '%')
print(output)

Output

12.340000%

Summary

In this Built-in Functions tutorial, we learned the syntax of the format() built-in function, and how to use this function to format the representation of a given value.