Tips of print()

In order to print more than 1 data in 1 print() function, following method are possible.

  • sep=xxx and end=xxx option
  • format method of string object

In [ ]:
# print hh:mm:ss

hh = 1
mm = 2
ss = 3

# simple
print(hh,':',mm,':',ss, sep='')

# smarter
print(hh,mm,ss, sep=':')

# format method
print('{}:{}:{}'.format(hh,mm,ss))

# format method length=2 leading-0
print('{:02}:{:02}:{:02}'.format(hh,mm,ss))

In [ ]:
# Print colxrow=col*row
col = 2
row = 3

# it's possible to specify the parameter
print('{1}x{0}={2:2}'.format(row, col, row*col))

I/O overhead

I/O system call is slow, and can be a bottle neck if print() function is called many time.


In [15]:
# Prepare 10000 random data

import random
rand_data = [random.randrange(1000) for i in range(10000)]

In [6]:
# print 1 by 1

def pr1(data):
    outfile = open('/dev/null', 'w')
    for x in data:
        print(x, file=outfile)
    outfile.close()

In [18]:
# print all in 1 print() function

def pr2(data):
    outfile = open('/dev/null', 'w')
    print('\n'.join(map(str,data)), file=outfile)
    print(file=outfile)  # for last new-line
    outfile.close()

In [16]:
# measure execution time

%timeit pr1(rand_data)


30.9 ms ± 175 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [19]:
%timeit pr2(rand_data)


6.17 ms ± 41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Printing multiple element with separator in 1 line

join() method of string object is a good choice. It takes iterable object of string as a parameter.


In [22]:
# use comma as a separator, last element does not have tailing comma

print(','.join(('abc', '123', 'xyz')))  # 1 tuple argument

# print 1-10 without trailing space

print(' '.join(map(str, range(1,11))))


abc,123,xyz
1 2 3 4 5 6 7 8 9 10

In [ ]: