Home      |       Contents       |       About

Prev: Booleans      |      Next: Input

Print

print()

  • In Python 3 'print' is a bulit-in function presenting results in the defined output device.
  • Formally the print syntax is as follows:
      print ([object, ...] [, sep=' '] [, end='\n'] [, file=sys.stdout] [, flush=False])
  • object: list of parameters for output
  • sep: separator symbol between items in object list
  • end: string defining the way the output pointer is placed after executing the print function
  • file: the output device (by default: the screen; could be some file)
  • flush: boolean value defining that output values should be flushed immediately to output device without buffering (when set to 'True'; the default is: 'False').
In [1]:
# Examples of using print()
x = 'spam'
y = 9
z = ['eggs']
print(x, y, z)
spam 9 ['eggs']
In [2]:
# no separator
print(x, y, z, sep='') 
spam9['eggs']
In [4]:
# comma and space as separator
print(x, y, z, sep=', ')
spam, 9, ['eggs']
In [6]:
# '#' as separator
print(x, y, z, sep='#')
spam#9#['eggs']
In [7]:
# no change of line for the next print that uses '-' separator
print(x, y, z, end='') 
print(x, y, z, sep='-')
spam 9 ['eggs']spam-9-['eggs']

Backslash '\'

  • Backslash:
    • a) escapes special characters in a string
    • b) breaks a logical line into more physical lines

Escape sequences

  • Certain strings introduced by backslash special character have a special meaning:

    • '\n' moves one line down (= LF, Line Feed)
    • '\r' moves to the beginning of line (= CR, Carriage Return)
    • '\t' moves to next tab (= 8 spaces)
  • See a table of Python escape sequences here (scroll down the page a bit)

In [14]:
# Displays x, y and moves to next line to display z
print(x, y, '\n', z)
spam 9 
 ['eggs']
In [15]:
# Displays in tabbed positions
print(x, y, z, sep='\t')
spam	9	['eggs']
In [16]:
# The separator moves to beginning of line after each variable is printed; so, finally only the value of z appears
print(x, y, z, sep='\r')
['eggs']

Escaping special characters = printing special characters as normal characters

In [1]:
print('Here backslash \'escapes\' single quotes')
print('No need for "backslash" here')
print('Here backslash escapes \\ backslash \\')
Here backslash 'escapes' single quotes
No need for "backslash" here
Here backslash escapes \ backslash \

Breaking lines

In [2]:
asum = 1+2+3+4+5+6+7+8+9+10+\
        11+12+13+14+15+16+17+18+19+20
print(asum)
210
  • Breaking lines can be done without backslash if the expression is enclosed in parentheses, brackets, etc.
In [20]:
print(1+2+3+4+5+6+7+8+9+10+
        11+12+13+14+15+16+17+18+19+20)
210
  • Use always '\' when breaking lines in prints with string literals
In [6]:
print('This is a long long long long long long long long long message')
print('This is a long long long long long\
long long long long message too')
This is a long long long long long long long long long message
This is a long long long long longlong long long long message too

Formatting output with the .format() method

  • For efficient printing of multiple values, use the .format() method work as follows:

  • STEP-1

    • Write a print() function with a string that contains as many {:} placeholders as the variables you want to display
    • Then add the .format() string at the end. Your print() appears now like this:
      print('{:}{:}{:}'.format())  
  • STEP-2

    • Add in placeholders description of the display space that is required.
    • Add in the format() parentheses the list of parameters to display. Now your print() looks like:
      print('{:5d} {:6.3f} {:10d}'.format(a,b,z))
    • For example {:5d} means preserve a space of 5 digits to present the value.
  • STEP-3 (optional)

    • Finally, you may define (if you wish) the order of appearence of the values. This can be done by adding numerical values representing the order in front of the ':' sign in placeholders
      print('{:5d} {:6.3f} {:10}'.format(a,b,z))
    • For example {2:5d} means present the value in the third place of .format() (remember Python is zero-ordered!)
In [27]:
a = 16
b = 2.25
z = 45
print('{:5d} {:6.3f} {:10d}'.format(a,b,z))
print('{2:5d} {1:6.3f} {0:10d}'.format(a,b,z))
   16  2.250         45
   45  2.250         16
  • In the above example: '5d' means reserving 5 spaces for digits, '6.3f' means reserving 6 digits for float, 3 of which for decimal part, '10d' (it could simply be '10') reserves 10-digit space for an integer (or string if 'd' is ommited).
In [30]:
a = 'Uno'
b = 'Dos'
z = 'Tres'
print('{2:5} {1:5} {0:5}'.format(a,b,z))
Tres  Dos   Uno  
  • See more on this Format Specification Mini-Language here

. Free learning material
. See full copyright and disclaimer notice