Python Printing and Formatting

The print() function normally displays a line of output.

In [1]:
print('Apple')
print('Banana')
print('Cherry')
Apple
Banana
Cherry

Suppressing the print() function's ending newline.

In [2]:
print('Apple', end=' ')
print('Banana', end=' ')
print('Cherry')
Apple Banana Cherry

When multiple arguments are passed, they are separated by spaces by default:

In [3]:
print('Apple', 'Banana', 'Cherry')
Apple Banana Cherry

To change the space separator, pass the sep argument:

In [4]:
print('Apple', 'Banana', 'Cherry', sep='*')

#remove the space:
print('Apple', 'Banana', 'Cherry', sep='')
Apple*Banana*Cherry
AppleBananaCherry

An escape character is a special character that is preceded with a backslash '\', appearing inside a string literal. Full list with examples: Python Escape Characters

In [5]:
#newline
print ('One\nTwo\nThree')

#a tab
print ('\tPrinting a tab')

#a backslash
print ('\\Printing a backslash')
One
Two
Three
	Printing a tab
\Printing a backslash

Formatting numbers with format specifiers.

In [6]:
num = 10000 / 3
num
Out[6]:
3333.3333333333335

Precision of two decimal places:

In [7]:
format(num, '.2f')
Out[7]:
'3333.33'

Comma separator and precision of two decimal places:

In [8]:
format(num, ',.2f')
Out[8]:
'3,333.33'

A minimum field width is the minimum number of spaces that should be used to display the value.

In [9]:
# min field width of 5 characters and 0 precision
format(num, '5.0f')
Out[9]:
' 3333'
In [10]:
# same as above, add coma separator
format(num, '5,.0f')
Out[10]:
'3,333'

Formatting a floating-point number as a percentage.

In [11]:
format (.5, '%')
Out[11]:
'50.000000%'
In [12]:
#0 precision
format (.5, '.0%')
Out[12]:
'50%'

Formatting an integer - 'd'.

Integer has no precision.

In [13]:
format (123456, 'd')
Out[13]:
'123456'

With a comma separator:

In [14]:
format(123456, ',d')
Out[14]:
'123,456'

In a field that is 8 spaces wide:

In [15]:
format(123456, '8,d')
Out[15]:
' 123,456'