Learn Python Easy Way - Print and Format

Let us look at some of the ways of using the print statement/function in Python.

amazon Echo

print("amazon","echo", sep="")

print("amazon","echo", sep=".")

print("amazon","echo", sep="-")

The sep is a parameter in the Print function. It is the Separator. You can specify anything as a separator here. If you just type "" or '' Quotes without a space between, then there will be no space between the words in the print function. I have demonstrated it above by making use of different special characters such as a dot, and a dash.

Incidentally you always have to type print in small letters. If you capitalize the P, it will result in error.

I have used Double Quotes in the Print function, you can also use single Quotes if you prefer it.

Escaping Quotes

You can use / a backward slash for escaping quotes. This can be helpful when you want to write a Apostrophe in the print statement. However you do not need escape character for printing double quotes.

print('It\'s obvious')
It's obvious

Format function

Now let us look at some of the ways the format function can be used inside print function

print("You can buy {} for {} Rupees per Kg" .format('Onions', 30))
You can buy Onions for 30 Rupees per Kg

This is an example of the format function. It makes use of the placeholders {}, you can add specifiers inside the {} that we sill see in further examples. You would write the text to be displayed in the print statement within Quotes, and add {} wherever needed. After the Quotes, you will write .format and write the arguments inside brackets. It can be text, numbers or even mathematical formula in it. An empty parenthesis would carry the sequence of the arguments in the .format(), whereas you can specify the sequence in the {} that we will see in other examples.

Moreover the arguments in the format() can include variables too.

Positional Index in the placeholders

print('This Train will start from {0} and stop at {1}' .format('Varanasi','Pune'))
This Train will start from Varanasi and stop at Pune

print('This Train will start from {1} and stop at {0}' .format('Varanasi','Pune'))
This Train will start from Pune and stop at Varanasi

Date and Time format

This is one of the important information we might need to print in out Python programs. Let us see the formatting of Date/Time. We need to use the module datetime for this

from datetime import datetime
print('The Train will start on {:%Y-%m-%d %H:%M}'.format(datetime(2018, 1, 17, 10, 20)))
The Train will start on 2018-01-17 10:20

Featured Post

Creating Games in Scratch for ICSE Class 6

An Introduction to Creating Games in Scratch  for ICSE Class 6 Hello friends, I hope you have already read the previous post on An Int...