Python format

The Python format function is one of the String functions used to format the output as per our requirements. This Python format function is one of the ways to format strings in print function. In this section, we explain to you how to use the format function in Python Programming with an example. The syntax of the Python format function in print is

{}.format(value)

Python format Example

The following set of examples helps to understand the Format function in Python Programming Language.

Python format String {} Example 1

The Python format string function uses curly braces {} as the replacement placeholders. It means one {} accepts one argument from format function.

# Python format example
 
print('{}'.format('Tutorial'))
 
print('{}'.format(25))

Python format String {} output

Tutorial
25

Here we declared a string variable, instead of providing the string value directly inside a print statement. Next, we called that msg using format function.

msg = 'Tutorial Gateway'

print('{}'.format(msg))
Tutorial Gateway

Python format string {} Example 2

The format function uses {} as the place holders for replacement fields. Anything that is outside the {} treated as the Python string literal, which prints as it is. In this Python format string example, the first statement replaces the {} with Hello and prints the World as it is. The second statement replaces the {} after the Learn with Python. The last one replaces the {} after the Employee Age is with 25.

print("{} World".format("Hello"))
 
print("Learn {} for Free!".format("Python"))
 
print("Employee Age is {}".format(25))
Hello World
Learn Python for Free!
Employee Age is 25

Python format Multiple arguments Example

We are using multiple arguments inside the format function. In this situation, the Python print format function uses the order that we specified inside the format.

For example, within the first statement, the first curly braces fill or replace with Tutorial, and the second curly braces replace with Gateway. It always follows the same order.

print('{} {}'.format('Tutorial', 'Gateway'))
 
print('{} {}'.format('Tutorial', 25))

format function with Multiple arguments output

Tutorial Gateway
Tutorial 25

Here we declared two variables. Next, we used those string variables inside a format function.

first_msg = 'Tutorial Gateway'
second_msg = 'Hello World'
 
print('{} {}'.format(first_msg, second_msg))
print('{} {}'.format(second_msg, first_msg))

format function with variables output

Tutorial Gateway Hello World
Hello World Tutorial Gateway

Python format Index Example

So far, we used the {}. That’s why those curly braces are replaced by the position of arguments in a format function. In this example, we used the index values to change the position.

The second statement prints 2nd argument at {1}, first argument value at {0}, and third argument value at {2} place holder.

first_msg = 'Tutorial Gateway'
second_msg = 'Hello World'
third_msg = 'Python'
 
print('{0}  {1}  {2}'.format(first_msg, second_msg, third_msg))
print('{1}  {0}  {2}'.format(first_msg, second_msg, third_msg))
print('{2}  {0}  {1}'.format(first_msg, second_msg, third_msg))
print('{2}  {1}  {0}'.format(first_msg, second_msg, third_msg))
python format 6

Python format using Key value Example

In python, you can also use the keyword parameters such as key = value within the format function.

In this String function example, within the first statement, key1 is lang and value1 = Python. Next, key2 = com and value2 = Tutorial Gateway. It means the key replaced by value1 and key2 with value2.

f_msg = 'Tutorial Gateway'
s_msg = 'Python'

print('Learn {lang} at {com}'.format(lang = s_msg, com = f_msg))
print('{com} Welcomes {lang}'.format(lang = s_msg, com = f_msg))

format function using Key value output

Learn Python at Tutorial Gateway
Tutorial Gateway Welcomes Python

Python format function to truncate string

You can use this format function to truncate the string as well. In this example, we show how to use the Python format function to truncate the string value.

The first statement truncate the string to the length of 5. The next statement truncates to length 7, and the third one returns the first 10 characters from a string.

msg = 'Tutorial Gateway'
 
print('{:.5}'.format(msg))
print('{:.7}'.format(msg))
print('{:.10}'.format(msg))
print('{:.{}}'.format(msg, 12))

Truncate string using a format function output

Tutor
Tutoria
Tutorial G
Tutorial Gat

Python format Options

The following are the list of available Python format options for alignment, signs, and binary formatting, etc.

  • ^ Aligns the result to the center.
  • < Aligns the result to the left side.
  • > Aligns the result to the right side.
  • = Place the sign to the leftmost position.
  • + Uses this sign to indicate if the result is positive or negative.
  • – Use this sign for Negative values only.
  • ‘ ‘ – For positive numbers, it uses a leading space.
  • , – It uses a comma as a thousand separator.
  • _ It uses underscore as a thousand separator.
  • b – binary format.
  • c – converts the given value into Unicode character.
  • d – decimal format.
  • e – Scientific format with e (Lowercase).
  • E – Scientific format with E (Uppercase).
  • f – Fixpoint number format.
  • F – Uppercase Fixpoint number format.
  • g – General format.
  • G – General format. For scientific notation, it uses E).
  • o – Octal format.
  • x – Lowercase Hexa format.
  • X – Uppercase Hexa format.
  • n – Number format.
  • % – Percentage format.

Python format string padding

As we said earlier, <, > and ^ used to align the given numbers or text to the left, right, or center. In this example, we use those operators along with format function to perform the alignment.

msg = 'tutorialgateway'
 
print("Align Center")
print('{:^40}'.format(msg))
print('{:*^40}'.format(msg))
print('{:@^{}s}'.format(msg, 40))
 
print("\nAlign Left")
print('{:25}'.format(msg))
print('{:*<25}'.format(msg))
print('{:@<{}s}'.format(msg, 25))
 
print("\nAlign Right")
print('{:>30}'.format(msg))
print('{:*>30}'.format(msg))
print('{:@>{}s}'.format(msg, 30))
Align Center
            tutorialgateway             
************tutorialgateway*************
@@@@@@@@@@@@[email protected]@@@@@@@@@@@@

Align Left
tutorialgateway          
tutorialgateway**********
[email protected]@@@@@@@@@

Align Right
               tutorialgateway
***************tutorialgateway
@@@@@@@@@@@@@@@tutorialgateway

format string padding analysis

  • print(‘{:^40}’.format(msg)) returns the message with the width of 40. Here, we used ^ before that 40. It means the message aligns in the center, and the total width is 40 (including spaces and text).
  • print(‘{:*^40}’.format(msg)) is same as the above statement. Instead of showing the empty spaces, we used * symbol. It means, all the empty spaces filled with * symbols.
  • print(‘{:@^{}s}’.format(msg, 40)) – You can also use curly braces as the width value, and assign that values as the format function argument. Here, we aligned msg to the right side with a width of 40 and the width filled with @ symbols.
  • print(‘{:25}’.format(msg)) or print(‘{:<25}’.format(msg)) returns the message with the width of 25. Here, < aligns the text to the left side and fills the remaining width with empty spaces.
  • print(‘{:>30}’.format(msg)) returns the msg with the width of 30. Here, > symbol aligns the text to the right side and fills the remaining width with empty spaces.

Python Number format Example

We used the Python print format function to format numbers. The second statement places a space before 95, and the third statement returns a positive sign before 95. The next two statements return the negative sign for the negative numbers.

print('{:d}'.format(95))
print('{: d}'.format(95))
print('{:+d}'.format(95))
print('{:d}'.format(-12))
print('{:-d}'.format(-12))
95
 95
+95
-12
-12

Python formatting Separators

Use a thousand separator or how to change the separator. The third statement uses comma as a thousands separator. The last statement returns the _ underscore as a thousand separator.

value = 100000
 
print('{:d}'.format(value))
print('{:n}'.format(value))
print('{:,}'.format(value))
print('{:_}'.format(value))
100000
100000
100,000
100_000

Padding using format in Python

You can use this format function to apply padding to the values. First, we declared a positive and negative integer. Next, we used the integer values for padding.

value = 100
value2 = -200
 
print('{:d}'.format(value))
print('{:10d}'.format(value))
print('{:<10d}'.format(value))
print('{:^10d}'.format(value))
 
print('{: d}'.format(value2))
print('{:=10d}'.format(value2))
print('{:=15d}'.format(value2))
100
       100
100       
   100    
-200
-      200
-           200

Padding using format analysis

  • print(‘{:10d}’.format(value)) means it takes 100 and assign the width as 10. Here, we haven’t specified the alignment <, >, or ^ so, it aligns 10 to the right side (default) with width 10.
  • print(‘{:<10d}’.format(value)) means 100 aligns to left side, and the width = 10.
  • print(‘{:^10d}’.format(value)) align 100 to centre and the width is 10.
  • print(‘{:=10d}’.format(value2)) keeps the negative sign to the left side and 200 on the right side. Here, the total width is 10.

Python format Float Example

You can use the Python print format function to format the float values. I mean, you can restrict the number fo decimals, or you can increase the decimal positions. For example, .2f means only 2 decimal positions, .4f means returns the value with 4 decimal positions by rounding the remaining values.

value = 10.9823764989
 
print('{:f}'.format(value))
print('{:.2f}'.format(value))
print('{:.3f}'.format(value))
print('{:.4f}'.format(value))
print('{:.5f}'.format(value))
print('{:.6f}'.format(value))
print('{:.7f}'.format(value))
10.982376
10.98
10.982
10.9824
10.98238
10.982376
10.9823765

Python format Integers and Decimals Example

Formatting the numeric values and float numbers using the format function.

value = 100
f_value = 15.957639
 
print('{:5d}'.format(value))
print('{:10d}'.format(value))
print('{:1d}'.format(value))
print('{:07d}'.format(value))
 
print('{:6.2f}'.format(f_value))
print('{:6.3f}'.format(f_value))
print('{:8.2f}'.format(f_value))
print('{:8.4f}'.format(f_value))
print('{:012.4f}'.format(f_value))
  100
       100
100
0000100
 15.96
15.958
   15.96
 15.9576
0000015.9576

In this Python format print example,

  • print(‘{:5d}’.format(value)) means it returns 100 with a width fo 5. If you specify any alignment, then 100 aligns to that side. Otherwise, by default, it aligns to the right side
  • print(‘{:07d}’.format(value)) means 100 returned with the width of 10. Here, all the empty spaces filled with 0 because of 07d.
  • print(‘{:6.2f}’.format(f_value)) returns f_value with two decimal places (.2f). Next, we specified the width as 6. So, it returns f_value with a width of 6.
  • print(‘{:012.4f}’.format(f_value)) takes 15.957639 and returns it with four decimal places. Here, the width value is 12, and we used 0 before that width value. So, 15.9576 return with a width of 12, and the remaining empty spaces filled with 0’s.

Python format Binary Examples

In this example, we are using all the existing format options. First, we declared value of 10000. Here, we are using that value to perform binary format, octal format, hexadecimal format, and numeric format.

Next, we used different values to return the Scientific format, general format, percentages, and fixed-point numbers.

value = 100000
 
print('{:d}'.format(value))
print('{:.2f}'.format(value))
print('{:b}'.format(value))
print('{:o}'.format(value))
print('{:x}'.format(value))
print('{:X}'.format(value))
print('{:n}'.format(value))
 
print('{:c}'.format(120))
 
print('{:e}'.format(5.00023455341))
print('{:E}'.format(5.00023455341))
 
print('{:f}'.format(25.98723453422))
print('{:F}'.format(25.98723453422))
 
print('{:g}'.format(15.987234534))
print('{:G}'.format(0.987234534))
 
print('{:.2}'.format(0.987234))
 
print('{:%}'.format(0.87))
100000
100000.00
11000011010100000
303240
186a0
186A0
100000
x
5.000235e+00
5.000235E+00
25.987235
25.987235
15.9872
0.987235
0.99
87.000000%

Python format Lists Example

Using the Python print format function to format the List items.

fruits = ['apple', 'mango', 'banana', 'cherry','kiwi']

print('Fruits List = {}'.format(fruits))

print('Fruit Item = {0[1]}'.format(fruits))
print('Fruit Item = {f[1]}'.format(f = fruits))

print('Fruit Item = {0[3]}'.format(fruits))
print('Fruit Item = {f[3]}'.format(f = fruits))

print('Fruit Item = {}'.format(*fruits))

format function on list items output

Fruits List = ['apple', 'mango', 'banana', 'cherry', 'kiwi']
Fruit Item = mango
Fruit Item = mango
Fruit Item = cherry
Fruit Item = cherry
Fruit Item = apple

Python format Dictionary Example

Use the format print function to format the dictionary items.

employee = {'name': 'John', 'age': 25, 'salary': 120000}

print('{} is {} years Old'.format(employee['name'], employee['age']))

print('At {1}, {0} is earning {2} income'.format( employee['name'], employee['age'], employee['salary']))

print('-------------')
print('{name} is {age} Years Old'.format(**employee)) 
print('At {age},{name} is earning {salary} income'.format(**employee))

print('-------------')
print('{emp[name]} is {emp[age]} Years Old'.format(emp = employee))
print('At {emp[age]}, {emp[name]} is earning {emp[salary]} income'.format(emp = employee))

format Dictionary output

John is 25 years Old
At 25, John is earning 120000 income
-------------
John is 25 Years Old
At 25,John is earning 120000 income
-------------
John is 25 Years Old
At 25, John is earning 120000 income