Search notes:

Python: print

print("%f"     % 3.141)           # 3.141000
print("%6.2f"  % 3.141)           #   3.14
print("%06.2f" % 3.141)           # 003.14  

ar=[1, 2, 3]
tu=(7, 8, 9)

print(ar)                         # [1, 2, 3]
print(tu)                         # (7, 8, 9)

print("%d %d %d"    %  tu)        # 7 8 9

print("{} {}".format(tu, 5))      # (7, 8, 9) 5


# print("%d %d %d" % ar)  # TypeError: %d format: a number is required, not list
Github repository about-python, path: /builtin-functions/print/demo.py

Write text without new lines

The parameter end controls what is printed after the text to be printed. Its default is the new line.
The following example assigns a whitespace to end so that multiple invocations of print write on the same line.
Alternatively, text without new lines can also be written with sys.stdout.write().
print('one', end = ' ')
print('two', end = ' ')
print('three')

import sys
sys.stdout.write('foo ' )
sys.stdout.write('bar ' )
sys.stdout.write('baz\n')
Github repository about-python, path: /builtin-functions/print/without-newlines.py

Print a list

If a list is passed to print(), the list is printed with the square brackets ([ elem, elem… ]).
In order to print the individual elements of the list, the list must be prepended with a * (unpacking operator):
lst = [ 'foo', 'bar', 'baz' ]
print(lst)
#
#  ['foo', 'bar', 'baz']

print(*lst)
#
#  foo bar baz
Github repository about-python, path: /builtin-functions/print/list.py

Print elements with a user defined separator

The sep parameter allows to define the separator with which the elements are printed.
print('foo', 'bar', 'baz', sep=', ')
#
#  foo, bar, baz(

lst = [ 'one', 'two', 'three' ]
print(*lst, sep=' - ')
#
#  one - two - three
Github repository about-python, path: /builtin-functions/print/sep.py

See also

The pprint standard library
Python: Built in functions

Index