TIME NOW CALENDAR CONVERT LENGTH CONVERT TEMPERATURE DICTIONARIES, LISTS SCIENCE EDUCATION RELIGION WORK CALCULATOR CALCULATE LIFE

Python 3 programming language, learn python, tutorial

ALL TOPICS

Python 3. Print output and format

1. repr formatting. Return a string containing a printable representation of an object. You get, what you type in interpreter.
s = 'Hello, world.'
# same representation, but plus ''
print ("1. ", str(s));
print ("2. ", repr(s))

# same representation
x = 10 * 3.25
y = 200 * 200

s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
print("3. ", s)

# different representation
hello = 'hello, world\n'
print("4. ", str(hello))

hellos = repr(hello)
print("4a. ", hellos)

print("5. ", (x, y, ('spam', 'eggs')))

# The argument to repr() may be any Python object:
print("5a.", repr((x, y, ('spam', 'eggs'))))

2. str.rjust() method of string objects, which right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods str.ljust() and str.center().
for x in range(1, 11):
print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')

# Note use of 'end' on previous line
print(repr(x*x*x).rjust(4))

for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))

3. Zerofill:
print ('12'.zfill(5), '-3.14'.zfill(7), '3.14159265359'.zfill(5))

4. print and format:
print('We are the {} who say "{}!"'.format('knights', 'Ni'))

print('{0} and {1}'.format('meter', 'mile'))

print('{1} and {0}'.format('meter', 'mile'))

print('The story about {0}, {1}, and {other}.'.format('lithuanian', 'latvian', other='estonian'))

5. '!a' (apply ascii()), '!s' (apply str()) and '!r' (apply repr()) can be used to convert the value before it is formatted:
import math

# repr and str are the same
print('The value of PI is approximately {}.'.format(math.pi))
print('The value of PI is approximately {!r}.'.format(math.pi))

# repr and str are NOT the same
print('The value of PI is approximately {}.'.format( str(math.pi) + "\n"))
print('The value of PI is approximately {!r}.'.format(str(math.pi) + "\n"))

6. Passing an integer after the ':' will cause that field to be a minimum number of characters wide.
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print('{0:10} ==> {1:10d}'.format(name, phone))

print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
'Dcab: {0[Dcab]:d}'.format(table))

print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))

7. Old sprintf style:
import math

print('The value of PI is approximately %5.3f.' % math.pi)

print('The value of PI is approximately %10.4f.' % math.pi)

8. Strings. Old and new formats:
# Old style
print ('%s %s' % ('meter', 'centimeter'))

# New style
print ('{} {}'.format('meter', 'cemtimeter'))

###
### New
###

print ('{1} {0}'.format('one', 'two'))

###
### Representation
###

# Old
print ('%r, %a, %s' % ('räpr\n', 'räpr\n', 'räpr\n'))

# New
print ('{0!r}, {0!a}, {0!s}'.format('räpr\n'))

###
### Align
###

# Old
print ('%-10s %s' % ('meter', 'centimeter'))

# New
print ('{:10} {}'.format('meter', 'centimeter'))

# New, fill characters
print ('{:_<20}'.format('meter ' * 2))

# New, fill characters
print ('{:_>20}'.format('meter ' * 2))

# New, fill characters
print ('{:_^20}'.format('meter ' * 2))

###
###

# Old
print ('%.5s' % ('centimeter',))

# New
print ('{:.5}'.format('centimeter'))

# Old
print ('%-10.5s %s' % ('centimeter', 'centimeter',))

# New
print ('{:10.5} {}'.format('centimeter',  'centimeter'))

# Old style
​x = "a"
y = 10

print ('%10.5s %s' % ('centimeter', 'centimeter',))
print ('%-10.5s %s' % ('centimeter', 'centimeter',))

Numbers:
###
### Num
###

# old style
print ('%d %d' % (1, 2))

# new style
print ('{} {}'.format(1, 2))

###
### Float
###

# Old
print ('%f' % (3.141592653589793,))

# New
print ('{:f}'.format(3.141592653589793))

import math
# float, 3 positions
print('The value of PI is approximately {0:.3f}.'.format(math.pi))

# Old
print ('%4d' % (12,))

# New
print ('{:4d}'.format(12))

# Old 0000xxx.xx
print ('%06.2f' % (3.141592653589793,))

# New 0000xxx.xx
print ('{:06.2f}'.format(3.141592653589793))

# Old - 4 positions
print ('%04d' % (12,))

# New - 4 positions
print ('{:04d}'.format(12))

# Old. Positive numbers with +
print ('%+d %+d' % (12, -12))

# New
print ('{:+d} {:+d}'.format(12, -12))

###
### Space
###

# Old. Spaces in numbers
print ('% d % d' % ((-  23),(23)))

# New
print ('{: d} {: d}'.format((-  23),(23)))

Parameters, variables:
data = {'first': 'meter', 'last': 'centimeter'}

# Old
print ('%(first)s %(last)s' % data)

# New
print ('{first} {last}'.format(**data))

# New
print ('{first} {last}'.format(first='meter', last='centimeter'))

# New - alias
person = {'first': 'Jean-Luc', 'last': 'Picard'}

print ('{p[first]} {p[last]}'.format(p=person))

# New. http://strftime.org
from datetime import datetime
print ('{:%Y-%m-%d %H:%M}'.format(datetime(2007, 1, 2, 3, 4)))

8.a. Sort acording IP. Format %3 is used:
ips = ["10.0.1.1", "100.0.0.20", "2.1.1.1", "193.168.0.1"]

for i in range(len(ips)):
ips[i] = "%3s.%3s.%3s.%3s" % tuple(ips[i].split("."))

ips.sort()

print("before: ", ips)

for i in range(len(ips)):
ips[i] = ips[i].replace(" ", "")

print("after: ", ips)

Task 1. Linux. Write processors load graph (1 minute average field) with stars. Show for every second. Run into terminal. Use format possibilities. If > 0.6, print in red. < 0.3 - green. Read data for 2 minutes every second. Example:
#!/usr/bin/python

import time
import os
import sys

# colors
RED   = "\033[1;31m"
BLUE  = "\033[1;34m"
CYAN  = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD    = "\033[;1m"
REVERSE = "\033[;7m"
HIGH= "\033[1;41m"
END = "\033[1;m"

# write initial color
sys.stdout.write(HIGH)

# print with color end
print ( '%s' %  load + END )

sys.stdout.write(RESET)
print ( '%s' %  load + END )

sys.stdout.write(GREEN)
print ( '%s' %  load + END )

time.sleep(5)

Result:

0.1   -  *
0.55  -  ******
0.9   -  *********
0.1   -  *
0.91  -  *********

ALL TOPICS