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('This {name} is {adjective}.'.format(name='kilometer', adjective='absolutely horrible'))
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))
6a. Two dictionaries are used to format text:
table1 = {'a': 'Sjoerd', 'b': 'Jack', 'c': 'Dcab'}
table2 = {'a': 4127 , 'b': 1, 'c': 7678}
print( '{0[a]:7s} {1[a]:5d}\n'
'{0[b]:7s} {1[b]:5d}\n'
'{0[c]:7s} {1[c]:5d}'.format(table1,table2))
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))
###
### Truncate, padding
###
# 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('This {name} is {adjective}.'.format(name=x, adjective=y))
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"
# load
load = str(os.getloadavg());
# 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 - *********
Linux commands:
1. Prisijungian root siteminiu administratorium,
turi rodyti # kairėj
2. Parodo koks vartotojas
whoami
3. Rodyklės iškviečia komandas
su
slaptažodis: vvk
4. Darbinis katalogas
pwd
5. Failo sukūrimas
touch hello.py
6. Kokie failai kataloge:
ls
ls -l
7. Navigacija
Aukščiausias taškas
cd /
Į katalogą
cd /etc
Į katalogą
cd /home/student
6. Failo turinys
cat hello.py
7.Siunstaliuoti mc redaktorių
apt-get install mc
8. Paleidžiam redaktorių:
mc
9. Atsistojam ant hello.py ir spaudžiam [F4],
Pasirenkam 2 variantą, kad naudotų mcedit komandą failo redagavimui.
10. Išsaugojimas [F2], išėjimas [esc], kai išsaugota
11. Kopijuojam iš naršyklės dešiniu klavišu pažymėtą tekstą.
Paste Linux-e atitinka [shift]+[insert]. Atidarytame su [F4]
faile spaudžiam [shift]+[insert].
12. Išėjus iš failo patikrinam, kur yra python
whereis python
Rodo: /usr/bin/python3.7
Tai pataisom hello.py pirmoje eilutėje
13. Tam, kad pasižiūrėti komandos rezultatus, kai paleistas mc spaudžiam [CTRL] + [O]. Pasižiūrim ir gryžtam vėl su [CTRL] + [O].
14. Suteikim failui vykdomąsias teises
chmod 777 /home/student/hello.py
15. Failo paleidimas einamąjame kataloge:
./hello.py
arba pilnas kelias
/home/student/hello.py
16. Jeigu failas pakimba, užima terminalą ir veikimas nesibaigia, užbaigiam [CTRL]+[C].
17. Python kodas rodo uptime komandos rezultatus:
1 min, 5 min, 15 min procesorių apkrovimus.