Python format()

Python format() builtin function is used to format given value/object into specified format.

In this tutorial, we will learn about the syntax of Python format() function, and learn how to use this function with the help of examples.

Syntax

The syntax of format() function is

</>
Copy
format(value, format)

where

ParameterDescription
valueA Python Object.
formatA String value. It’s the ‘format’ we want to format the given value into.
The following are legal values for format.
'<' – Left aligns the result (within the available space)
'>' – Right aligns the result (within the available space)
'^' – Center aligns the result (within the available space)
'=' – Places the sign to the left most position
'+' – Use a plus sign to indicate if the result is positive or negative
'-' – Use a minus sign for negative values only
' ' – Use a leading space for positive numbers
',' – Use a comma as a thousand separator
'_' – Use a underscore as a thousand separator
'b' – Binary format
'c' – Converts the value into the corresponding unicode character
'd' – Decimal format
'e' – Scientific format, with a lower case e
'E' – Scientific format, with an upper case E
'f' – Fix point number format
'F' – Fix point number format, upper case
'g' – General format
'G' – General format (using a upper case E for scientific notations)
'o' – Octal format
'x' – Hex format, lower case
'X' – Hex format, upper case
'n' – Number format
'%' – Percentage format

Returns

The function returns the formatted value of given argument.

Examples

1. Format Value with Hex format

In this example, we take an integer value and format it to Hex – upper case.

Python Program

</>
Copy
a = 31
result = format(a, 'X')
print(result)

Output

1F

2. Format value with Comma as Thousand Separator

In this example, we take an integer value and format it with comma as thousand separator.

Python Program

</>
Copy
a = 52368996
result = format(a, ',')
print(result)

Output

52,368,996

3. Format Value with Percentage format

In this example, we take an integer value and format it to percentage value.

Python Program

</>
Copy
a = 0.31
result = format(a, '%')
print(result)

Output

31.000000%

4. Invalid Format Specifier

If we pass an invalid string value for format parameter, then format() raises ValueError with the message ‘Invalid format specifier’.

Python Program

</>
Copy
a = 52368996
result = format(a, 'bb')
print(result)

Output

ValueError: Invalid format specifier

Conclusion

In this Python Tutorial, we have learnt the syntax of Python format() builtin function, and also learned how to use this function, with the help of Python example programs.