Python print format

In this post, we are going to see how to format String, floating number when you print them.
It is good to know various types for print formatting as you code more and more, so that you can print them in best way possible.

The most basic example of a print statement is:

print('Welcome to code2master')

Output:

Welcome to code2master

Strings

You can use the %s to format strings into your print statements.

name='John' print('Welcome %s to the code2master!!' %(name))

Output:

Welcome John to the code2master!!

Floating Point Numbers

Floating point numbers use the format %n1.n2f where the n1 is the total minimum number of digits the string should contain (these may be filled with whitespace if the entire number does not have this many digits.) The n2 is for number of decimal places you want.
Lets see some examples:

print('Floating point numbers upto 2 decimal places: %1.2f' %(34.2336)) print('Floating point numbers upto 3 decimal places: %1.3f' %(34.2336)) print('Floating point numbers upto 0 decimal places: %1.0f' %(34.2336)) print('Floating point numbers upto 2 decimal places with minimum 10 digits: %10.2f' %(34.2336)) print('Floating point numbers upto 2 decimal places with minimum 15 digits: %15.2f' %(34.2336))

Output:

Floating point numbers upto 2 decimal places: 34.23
Floating point numbers upto 3 decimal places: 34.234
Floating point numbers upto 0 decimal places: 34
Floating point numbers upto 2 decimal places with minimum 10 digits: 34.23
Floating point numbers upto 2 decimal places with minimum 15 digits: 34.23

Multiple Formatting

You can pass a tuple to the modulo symbol to place multiple formats in your print statements:
For example

print('Name: %s, Age: %1.0f, Sex: %s' %('John',20,'Male'))

Output:

Name: John, Age: 20, Sex: Male

Using the string’s format() method

You can also use String’s format method to do the formatting.
Syntax

‘String here {var1} then also {var2}’.format(var1=’value1′,var2=’value1′)
You need to put variables in {} and pass the values to the argument of format method,
Lets see some examples:

print('Name: {name}, Age: {age}, Sex: {sex}'.format(name='John',age=20,sex='Male'))

Output:

Name: John, Age: 20, Sex: Male

That’s all about formatting in python

Leave a Reply

Your email address will not be published. Required fields are marked *