Post

Python format() Method

In this tutorial , we will learn about python format() method and its uses.

Python format() Method

What is python format() method?

The format() is a built-in pythonmethod that returns a formatted representation of the specified value.

The syntax of format() is:

1
2
format(value1, value2)

format() Parameters

The format()methods takes single parameters but multiple arguments:

  • values - one or more values that needed to be formatted.

format() Placeholders

The placeholders can be identified using names indexes {value}, numbered indexes like {0} , {1},etc. Or even empty {} placeholder.

Let’s check a simple example of the format()method.

Example 1: Simple formatting using format() method.

1
2
3
4
5
6
7
8
my_string = "Python"

print("We are learning {} from Pythonscholar.com".format("Python"))

print("We are learning {} from Pythonscholar.com".format(my_string))

print("We are learning {1} from {0}".format("Pythonscholar.com","Python"))

Output:

1
2
3
4
We are learning Python from Pythonscholar.com
We are learning Python from Pythonscholar.com
We are learning Python from Pythonscholar.com

Formatting Specifiers

format() method also supports different types for formatting specifiers that helps to manipulate the results.

:<Result will be aligned left
:>Result will be aligned right
:^Result will be aligned center
:=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 space to insert an extra space before positive numbers (and a minus sign before negative numbers)
:,Use a comma as a thousand separator
:_Use a underscore as a thousand separator
:bBinary format
:cConverts the value into the corresponding unicode character
:dDecimal format
:eScientific format, with a lowercase e
:EScientific format, with an uppercase E
:fFix point number format
:FFix point number format, in uppercase format (show inf and nan as INF and NAN)
:gGeneral format
:GGeneral format (using a upper case E for scientific notations)
:oOctal format
:xHex format, lower case
:XHex format, upper case
:nNumber format
:%Percentage format

Example 2: Using format specifiers with format() method.

1
2
3
4
print("The value is : {:x}".format(500))
print("The value is : {:%}".format(0.80))
print("The value is: {:5}".format(40))

Output:

1
2
3
4
The value is : 1f4
The value is : 80.000000%
The value is:    40

Rules of format()

There are no such rules to follow in the format() method.

This post is licensed under CC BY 4.0 by the author.