Learning Python Episode One

See also

Second episode Learning Python Episode Two!

'ciao'
'ciao'

Formatting

# Formatting expression
'%s, eggs, and %s' % ('spam', 'SPAM!')
'spam, eggs, and SPAM!'
# Formatting method
'{0}, eggs, and {1}'.format('spam', 'SPAM!')
'spam, eggs, and SPAM!'
# Numbers are optional
'{}, eggs, and {}'.format('spam', 'SPAM!')
'spam, eggs, and SPAM!'
M = [[1,2,3],[5,4,2]]
M
[[1, 2, 3], [5, 4, 2]]
x = 4
while x > 0:
    print('spam!' * x)
    x -= 1
spam!spam!spam!spam!
spam!spam!spam!
spam!spam!
spam!
zip?

Mapping Operations

bob1 = dict(name='Emanuele', job='Engineer!', age='31')
bob1
{'age': '31', 'job': 'Engineer!', 'name': 'Emanuele'}
temp = zip(['name', 'age', 'job'],['Emanuele', '31', 'Engineer!'])
print(temp)
type(temp)
[('name', 'Emanuele'), ('age', '31'), ('job', 'Engineer!')]
list

In Python3 temp is a zip object:

>>> print(temp)
<zip object at 0x7698f6c0>
dict(temp)
{'age': '31', 'job': 'Engineer!', 'name': 'Emanuele'}

Missing Keys: if Tests

D = {'a': 1, 'b': 2, 'c': 3}
D
{'a': 1, 'b': 2, 'c': 3}
D['e'] = 99
D
{'a': 1, 'b': 2, 'c': 3, 'e': 99}
'f' in D
False
if not 'f' in D:
    print('missing WTF!')
missing WTF!

Index with default value

value = D.get('x', 0)
value
0

if/else expression form

value = D['x'] if 'x' in D else 0
value
0

Iteration and Optimization

temp = [x ** 2 for x in [1, 2, 3, 4, 5]]
temp
[1, 4, 9, 16, 25]
temp = []
for x in [1, 2, 3, 4, 5]:
    temp.append(x ** 2)
temp
[1, 4, 9, 16, 25]

Tuples

T = (1, 2, 3, 4)
len(T)
4
T + (5, 6)
(1, 2, 3, 4, 5, 6)
T.index(3) # 3 appears at offset 2
2
T.count(4) # 4 appears once
1
T[0] = 123 # immutable
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-35-392e8b7c48f8> in <module>()
----> 1 T[0] = 123


TypeError: 'tuple' object does not support item assignment
T = (2,) + T[1:]
T
(2, 2, 3, 4)
# one item tuples require a trailing comma!
type((2,))
tuple
# parentheses can be omitted where commas don't otherwise matter
T = 'spam', 3.0, [11, 12, 34]
T
('spam', 3.0, [11, 12, 34])
[ord(x) for x in 'spaam']
[115, 112, 97, 97, 109]
# Generator of values
gen = (ord(x) for x in 'spaaam')
for x in gen:
    print x
115
112
97
97
97
109

Files

# writing the file
f = open('data.txt', 'w')
f.write('Ciao\n')
f.write('Bello!\n')
f.close()
# reading the file
f = open('data.txt', 'r') # r default
text = f.read()
text
'CiaonBello!n'
print(text)
Ciao
Bello!
text.split()
['Ciao', 'Bello!']
for line in open('data.txt'): print(line)
Ciao

Bello!
f.tell()
12L
f.seek(5)
print(f.read())
Bello!

Binary Bytes Files

# writing binary data
import struct
packed = struct.pack('>i4sh', 7, b'spam', 8)
packed
'x00x00x00x07spamx00x08'
file = open('data.bin', 'wb')
file.write(packed)
file.close()
# reading binary data
data = open('data.bin', 'rb').read()
data
'x00x00x00x07spamx00x08'
data[4:8]
'spam'
list(data)
['x00', 'x00', 'x00', 'x07', 's', 'p', 'a', 'm', 'x00', 'x08']
struct.unpack('>i4sh', data)
(7, 'spam', 8)
len(data) # length in bytes
10

Unicode Text Files

S = u'sp\xc4m'
print(S) # for Python 2.x
S # for Python 3.x
spÄm
print(S[2])
Ä
import codecs # required for Python 2.X
file = codecs.open('unidata.txt', 'w', encoding='utf-8') # Write/encode UTF-8 text
file.write(S)
file.close()
text = codecs.open('unidata.txt', encoding='utf-8').read() # Read/decode UTF-8 text
print(text) # for Python 2.x
text # for Python 3.x
spÄm
u'spxc4m'
len(text)
4
# Read raw encoded bytes
raw = open('unidata.txt', 'rb').read()
raw
'spxc3x84m'
# raw/undecoded too
open('unidata.txt').read() # Python 2.x same as above
'spxc3x84m'
len(raw)
5
text.encode('utf-8') # encode to bytes
'spxc3x84m'
raw.decode('utf-8') # decode to str
u'spxc4m'
text.encode('latin-1')
'spxc4m'
text.encode('utf-16')
'xffxfesx00px00xc4x00mx00'
S = b'\xff\xfes\x00p\x00\xc4\x00m\x00'.decode('utf-16')
print(S) # Python 2.x
S # Python 3.x
spÄm
S
u'spxc4m'

Other Core Types

Sets

X = set('spaaaaam')
Y = {'h', 'a', 'm'}
X, Y
({'a', 'm', 'p', 's'}, {'a', 'h', 'm'})
X & Y
{'a', 'm'}
{n ** 2 for n in [1,2,3,4]}
{1, 4, 9, 16}
list(set([1, 2, 1, 4, 1])) #Filtering out duplicates
[1, 2, 4]
set([1, 2, 1, 4, 1])
{1, 2, 4}
set('ciao') == set('oaic')
True
'p' in set('spam'), 'p' in 'spam', 'ham' in ['eggs']
(True, True, False)

Floating-point, Decimals & Fractions

1.0 / 3 # A .0 is required in Python 2.x
0.3333333333333333
(2.0/3) + (1.0/2)
1.1666666666666665
import decimal
d = decimal.Decimal('3.141')
d + 1
Decimal('4.141')
decimal.getcontext().prec = 3 # decimal precision
decimal.Decimal('1.00') / decimal.Decimal('3.00')
Decimal('0.333')
from fractions import Fraction # Fractions: numerator+denominator
f = Fraction(2, 3)
f + 1
Fraction(5, 3)
f + Fraction(1, 2)
Fraction(7, 6)

The type Object

L = [1, 2, 4]
print(type(L)) # in Python 2.x
type(L) # in Python 3.x
<type 'list'>
type(L) == type([])
True
if type(L) == list:
    print(True)
True
True if type(L) == list else False
True
True if isinstance(L, list) else False
True
class Worker:
    def __init__(self, name, pay):
        self.name = name
        self.pay = pay
    def lastName(self):
        return self.name.split()[-1]
    def giveRaise(self, percent):
        self.pay *= (1.0 * percent)
ema = Worker('Emanuele Disco', 1000000)
ema.lastName()
'Disco'

Numeric Literals

bin(5)
'0b101'
repr(3)
'3'
repr(ema) # Return the canonical string representation of the object.
`ema` # same as above removed in Python 3.x
'<__main__.Worker instance at 0x28ef6e8>'
str(ema)
'<__main__.Worker instance at 0x28ef6e8>'
x = [1,2,3,4]
x[0:3:2] # is equivalent to x[slice(0, 3, 2)]
[1, 3]
x[slice(0, 3, 2)]
[1, 3]
a = 3
b = 4
a + 1, a - 1
(4, 2)
b * 3, b / 2.0
(12, 2.0)
a % 2
1
b / ( 2.0 + a )
0.8
str(b / ( 2.0 + a ))
'0.8'
num = 1 / 3.0
num # auto echoes
0.3333333333333333
print(num) # print explicitly
0.333333333333
'%e' % num # string formatting expression
'3.333333e-01'
'%4.3f' % num
'0.333'
'{0:4.2f}'.format(num)
'0.33'
repr('spam')
"'spam'"
str('spam')
'spam'
repr("spam")
"'spam'"

Comparisons: Normal and Chained

2.0 >= 1
True
X = 2
Y = 4
Z = 6
X < Y < Z
True
False < 3
True
1.1 + 2.2
3.3000000000000003
int(1.1 + 2.2) == int(3.3)
True

Division: Classic, Floor, and True

X / Y # classic in Python 2.x and true division in Python 3.x
0
X // Y # floor division
0
6 // 5
1
import time
time.sleep(.1)
10 // 4.0
2.0

Use the following module to enable Python 3.x / behaviour

from __future__ import division # enable Python 3.x / behaviour
10 / 4
2.5

Division in Python 3.X

The // operator is called truncating but is more accurate to refer to it as floor.

5 / 2, 5 / -2
(2.5, -2.5)
# (2, -3) in Python 2.x
5 // 2, 5 // -2 # same in Python 2,x
(2, -3)
5 / 2.0, 5 / -2.0 # same in Python 2,x
(2.5, -2.5)
5 // 2.0, 5 // -2.0 # same in Python 2,x
(2.0, -3.0)
import math
math.floor(2.5)
2.0
math.floor(-2.5)
-3.0
math.trunc(2.3)
2
math.trunc(-2.6)
-2
5 / -2
-2.5
# -3 in Python 2.x
math.trunc(5 / -2) # in Python 3.x
-2
math.trunc(5 / float(-2)) # in Python 2.x
-2
1 % 8 # remainder
1

Hex, Octal, Binary

0o1, 0o20, 0o377 # octal
(1, 16, 255)
0x01, 0x10, 0xFF # hex
(1, 16, 255)
(0b1, 0b10000, 0b11111111)
(1, 16, 255)
oct(64), hex(64), bin(64)
('0100', '0x40', '0b1000000')
64, 0o100, 0x40, 0b10000000
(64, 64, 64, 128)
int('64'), int('100', 8), int('40', 16), int('100000', 2)
(64, 64, 64, 32)
int('0x40', 16)
64
eval('64'), eval('0o34'), eval('0x34'), eval('0b110101')
(64, 28, 52, 53)
'{0:o}, {1:x}, {2:b}'.format(64,64,64)
'100, 40, 1000000'
'%o, %x, %x, %X' % (64, 64, 255, 255)
'100, 40, ff, FF'
# the old octal in Python 2.x
01, 020, 0377 # error in Python 3.x
(1, 16, 255)
X = 0x12312123123123
X
5120567972868387L
oct(X)
'0221422044304430443L'

Bitwise Operations

x = 1 # 1 decimal is 0001 in bits
x << 2 # shift left 2 bits
4
x | 2 # Bitwise OR
3
x & 1 # Bitwise AND
1
X = 0b0001
X << 2
4
bin(X << 2)
'0b100'
bin(X | 0b010)
'0b11'
bin(X & 0b1) # bitwise AND: both
'0b1'
X = 0xFF
bin(X)
'0b11111111'
X ^ 0b111111 # bitwise XOR: either but not both
192
X = 99
bin(X), X.bit_length(), len(bin(X)) - 2
('0b1100011', 7, 7)
import math
math.pi, math.e
(3.141592653589793, 2.718281828459045)
math.sqrt(144), math.sqrt(2)
(12.0, 1.4142135623730951)
min(1,4,8,3), max(5,4,1,1), min([1,5,7])
(1, 5, 1)
math.floor(2.5), math.floor(-2.3)
(2.0, -3.0)
int(2.5123), int(-2.634)
(2, -2)
round(2.523), round(2.4123), round(2.567, 2)
(3.0, 2.0, 2.57)
# round for display
'%.1f' % 2.567, '{0:.2f}'.format(2.567)
# this format produce strings
('2.6', '2.57')
(1 / 3.0), round(1 / 3.0, 2), ('%.2f' % (1 / 3.0))
(0.3333333333333333, 0.33, '0.33')
#square three methods
import math # Module
math.sqrt(144)
12.0
144 ** .5 # expression
12.0
pow(144, .5)
12.0
import random
random.random()
0.9649111804202926
random.randint(1, 10)
9
random.choice(['1', '5', '123123'])
'5'
pinco = ['lol', 'spam', 'che palle']
random.shuffle(pinco)
pinco
['che palle', 'spam', 'lol']
0.1 + 0.1 + 0.1 - 0.3
5.551115123125783e-17
print(0.1 + 0.1 + 0.1 - 0.3)
5.55111512313e-17

Decimal basics

from decimal import Decimal
Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')
Decimal('0.0')
Decimal.from_float(1.231) # convert float -> decimal
Decimal('1.2310000000000000941469124882132746279239654541015625')
Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
Decimal(1) / Decimal(7) # default 28 digits
Decimal('0.1428571428571428571428571429')
# Fixed precition
import decimal
decimal.getcontext().prec = 4
Decimal(1) / Decimal(7)
Decimal('0.1429')
Decimal(0.1) + Decimal(0.1) + Decimal(0.1) - Decimal(0.3)
Decimal('1.110E-17')
1999 + 1.33
2000.33
decimal.getcontext().prec = 2
pay = Decimal(str(1999 + 1.33))
pay
Decimal('2000.33')
# decimal context manager
with decimal.localcontext() as ctx:
    ctx.prec = 6
    d = Decimal('1.00') / Decimal('3.00')
    print(repr(d))
Decimal('0.333333')
d = Decimal('1.00') / Decimal('3.00')
print(repr(d))
Decimal('0.33')

Fraction Type

from fractions import Fraction
x = Fraction(1, 3)
y = Fraction(4, 6)
x
Fraction(1, 3)
print(y)
2/3
x + y
Fraction(1, 1)
Fraction('.25')
Fraction(1, 4)
a = 1 / 3.0 # only as accurate as floating-point hardware
b = 4 / 6.0
a, b
(0.3333333333333333, 0.6666666666666666)
a + b
1.0
0.1 + 0.1 + 0.1 - 0.3
5.551115123125783e-17
from fractions import Fraction
Fraction(1, 10) + Fraction(1, 10) + Fraction(1, 10) - Fraction(3, 10)
Fraction(0, 1)
from decimal import Decimal
Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')
Decimal('0.0')
1 / 3.0
0.3333333333333333
Fraction(1, 3)
Fraction(1, 3)
import decimal
decimal.getcontext().prec = 2
Decimal(1) / Decimal(3)
Decimal('0.33')
(1 / 3.0) + (6 / 12.0)
0.8333333333333333
Fraction(6, 12)
Fraction(1, 3)
Fraction(1, 3) + Fraction(6, 12)
Fraction(5, 6)
decimal.Decimal(str(1/3.0)) + decimal.Decimal(str(6/12.0))
Decimal('0.83')
str(1/3.0)
'0.333333333333'
1 / 3 # in Python 3.x
# = 0.333333333333333314829616256247390992939472198486328125
0.3333333333333333
str(1/3.0)
'0.333333333333'

Fraction convertions

(2.5).as_integer_ratio()
(5, 2)
f = 2.5
z = Fraction(*f.as_integer_ratio()) # convert float ->  fraction
z
Fraction(5, 2)
f.as_integer_ratio()
(5, 2)
(1/3.0).as_integer_ratio()
(6004799503160661L, 18014398509481984L)
x = Fraction(1, 3)
float(x) # convert fraction -> float
0.3333333333333333
Fraction.from_float(1.75) # convert float -> fraction
Fraction(7, 4)
Fraction(*(1.75).as_integer_ratio())
Fraction(7, 4)
x
Fraction(1, 3)
x + 2
Fraction(7, 3)
x + 2.0
2.3333333333333335
x + (1./3)
0.6666666666666666
x + Fraction(4, 3)
Fraction(5, 3)
4.0 / 3
1.3333333333333333
(4.0 / 3).as_integer_ratio()
(6004799503160661L, 4503599627370496L)
x
Fraction(1, 3)
a = x + Fraction(*(4.0 / 3).as_integer_ratio())
a
Fraction(22517998136852479, 13510798882111488)
22517998136852479 / 13510798882111488.
1.6666666666666667
a.limit_denominator(10)
Fraction(5, 3)

Sets basics in Python 2.6 and earlier

y = set('abcgsdf')
x = set('abcnbcx')
x, y
({'a', 'b', 'c', 'n', 'x'}, {'a', 'b', 'c', 'd', 'f', 'g', 's'})
print(x) # Python <= 2.6 display format
set(['a', 'x', 'c', 'b', 'n'])
x - y # difference
{'n', 'x'}
x | y # union
{'a', 'b', 'c', 'd', 'f', 'g', 'n', 's', 'x'}
x ^ y # xor
{'d', 'f', 'g', 'n', 's', 'x'}
'e' in x
False
z = x.intersection(y)
print(z)
set(['a', 'c', 'b'])
z.add('SPAM')
print(z)
set(['a', 'c', 'b', 'SPAM'])
z.update(['x', 'y'])
print(z)
set(['a', 'c', 'b', 'SPAM', 'y', 'x'])
z.remove('c')
print(z)
set(['a', 'b', 'SPAM', 'y', 'x'])
for item in set('abc'): print(item * 4)
aaaa
cccc
bbbb
S = set([1, 2, 3])
S | set([3, 4]) # union between sets
{1, 2, 3, 4}
S | [3, 4] # require both to be sets
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-3-7e2ecfb4bd18> in <module>()
----> 1 S | [3, 4]


TypeError: unsupported operand type(s) for |: 'set' and 'list'
S.union([3, 5]) # their methods allow any iterable
{1, 2, 3, 5}
S.intersection((1,2,3,4,5))
{1, 2, 3}
S.issubset(range(-5,6))
True

Set literals in Python 3.x and 2.7

S = set([1, 2, 3, 4]) # built-in
print(S)
set([1, 2, 3, 4])
S = {1, 2, 3, 4} # newer set literals
print(S)
set([1, 2, 3, 4])
S1 = {1, 2, 3, 4}
S1 & {1, 3}
{1, 3}
S1 > {1, 3}
True
S = set({}) # init an empty set
S.add(1.23)
S
{1.23}
{1, 2, 3} | {1}
{1, 2, 3}
# only immutable objects work in a set
S
S.add([1,2])
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-20-077718e65280> in <module>()
      1 # only immutable objects work in a set
      2 S
----> 3 S.add([1,2])


TypeError: unhashable type: 'list'
S.add({'a': 1}) # dict unhashable
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-21-908b7e066db8> in <module>()
----> 1 S.add({'a': 1})


TypeError: unhashable type: 'dict'
S.add((1, 2, 3)) # tuple OK
S
{1.23, (1, 2, 3)}
(1, 2, 3) in S
True

Set comprehensions in Python 3.X and 2.7

{x ** 2 for x in [1, 2, 6, 3]}
{1, 4, 9, 36}
{x for x in 'spam'} # same as set('spam')
{'a', 'm', 'p', 's'}
L = [1, 2, 3, 1, 7, 1 , 1, 2]
set(L)
{1, 2, 3, 7}
L = list(set(L)) # order may change
L
[1, 2, 3, 7]
set([1, 3, 5, 7]) - set([1, 2, 4, 5, 6])
{3, 7}
set('abcgqwe') - set('asdvvwer')
{'b', 'c', 'g', 'q'}
S = set(dir(bytes)) - set(dir(bytearray)) # in bytes but not in bytearray
print(S)
set(['__getslice__', 'format', '__mod__', '_formatter_field_name_split', 'encode', '__rmod__', '__getnewargs__', '_formatter_parser'])
S = set(dir(bytearray)) - set(dir(bytes))
print(S)
set(['insert', 'reverse', 'extend', '__delitem__', 'fromhex', '__setitem__', 'pop', '__iter__', '__iadd__', 'remove', 'append', '__alloc__', '__imul__'])
L1, L2 = [1, 3, 4, 5], [5, 3, 4, 1]
L1 == L2
False
set(L1) == set(L2)
True
sorted(L1) == sorted(L2)
True
'spam' == 'psam', set('spam') == set('asmp'), sorted('spam') == sorted('pmas')
(False, True, True)
engineers = {'bob', 'sue', 'ann', 'vic'}
managers = {'tom', 'sue'}
'bob' in engineers
True
engineers & managers
{'sue'}
engineers | managers
{'ann', 'bob', 'sue', 'tom', 'vic'}
engineers - managers
{'ann', 'bob', 'vic'}
engineers > managers
False
(managers | engineers) - (managers ^ engineers) # intersection
{'sue'}

Booleans

True + 4
5
print(type(True))
<type 'bool'>
isinstance(True, int)
True
True == 1
True
9 ** 0.5
3.0
import math
math.sqrt(9)
3.0
pow(3, 2)
9
9 ** .5
3.0
pow(3, 2)
9
int(4.234) # truncate a float
4
math.trunc(5.623)
5
round(4.512312, 2)
4.51
math.floor(4.7123 / 2)
2.0
float(5) # convert int => float
5.0
from __future__ import division
5 / 1 # convert int => float for Python 3.X
5.0
'%.2f' % (2.5123) # format a float with the % formatting expression
'2.51'
'%x' % (255) # convert an int to hex with % formatting expression
'ff'
'{0:.2f}'.format(2.3423) # format a float with string format method
'2.34'
'%o, %x, %X' % (64, 64, 64)
'100, 40, 40'
'{:o}, {:x}, {:b}'.format(64, 64, 64)
'100, 40, 1000000'
'{0:o}, {1:x}, {2:b}'.format(64, 64, 64)
'100, 40, 1000000'
int('FF', 16) # convert an hex => int
255
int('1011', 2) # convert a binary => int
11
int('0o100', 8) # convert oct => int
64
int('10000', 2)
16
eval('0o100')
64

Variables, Objects, References

L1 = [2, 4, 6]
L2 = L1[:] # copy the list to L2
L2
[2, 4, 6]
L2 = list(L1) # make a copy using constructor
L2
[2, 4, 6]
import copy
L2 = copy.copy(L1) # make a copy using the module copy
L2
[2, 4, 6]
L2 = copy.deepcopy(L1) # make a deep copy
L2
[2, 4, 6]
import sys
sys.getrefcount(1) # reference count for an object
1360

Strings

r'\temp\spam' # raw strings
'\temp\spam'
print('s\np\ta\x00m') # escape sequence
s
p   am
b = b'sp\xc4m'
b
'spxc4m'
print(u'sp\u00c4m')
spÄm
type(b'sp\xc4m')
str
title = 'this' ' is' " a test"
title
'this is a test'
s = 'a\0b\0c' # \0 Null:binary 0 character
s
'ax00bx00c'
len(s)
5
s = '\001\002\x03'
s # python display nonprintable chars in hex
'x01x02x03'
x = 'C:\pasd\qwe'
x
'C:\pasd\qwe'
x = '\0'
x
'x00'
print(x)

len(x)
1

Raw Strings

# raw strings
# r turn off the escape mechanism
myfile = open(r'\home\pi\script.php', 'w')
myfile
<open file '\home\pi\script.php', mode 'w' at 0xf56650>
path = r'C:\nsd\twe.dat'
path
'C:\nsd\twe.dat'
print(path)
C:nsdtwe.dat
r'...\' # a raw string cannot end with a backslash
  File "<ipython-input-50-3a2c1f40ff86>", line 1
    r'...\'
          ^
SyntaxError: EOL while scanning string literal
r = r'...\\'[:-1] # if u want to end a string with a backslash
print(r)
...
len('abc')
3
'abc' + 'def'
'abcdef'
'Ni!' * 4
'Ni!Ni!Ni!Ni!'
print('-' * 50)
--------------------------------------------------
myjob = 'hacker'
for c in myjob: print c
h
a
c
k
e
r
"k" in myjob
True
'spam' in 'acasdqwqwe'
False

Indexing and slicing

S = 'spam'
S[0], S[-2]
('s', 'a')
S[:], S[1:3]
('spam', 'pa')
S[-2], S[len(S)-2]
('a', 'a')
S[::-1], S[::2] # stride
('maps', 'sa')
'spam'[1:3]
'pa'
'spam'[slice(1, 3)]
'pa'
'spam'[::-1], 'spam'[slice(None, None, -1)]
('maps', 'maps')
import sys
print(sys.argv) # argv -- command line arguments
['/home/pi/python_example/ipython/lib/python2.7/site-packages/ipykernel/__main__.py', '-f', '/home/pi/.local/share/jupyter/runtime/kernel-f18712dd-c818-40e4-a909-e4d4fb9148e1.json']
sys.argv[1:]
['-f',
 '/home/pi/.local/share/jupyter/runtime/kernel-f18712dd-c818-40e4-a909-e4d4fb9148e1.json']

String Convertion Tools

repr(43)
'43'
str(32)
'32'
print str('spam'), repr('spam')
spam 'spam'
print(str('spam'), repr('spam')) # Raw interactive echo display
('spam', "'spam'")
str(3.123)
'3.123'
ord('A') # str => integer code
65
chr(65) # integer code => str
'A'
ord('0')
48
ord('5') - ord('0')
5
B = '1101'
I = 0
while B != '':
    I = I * 2 + (ord(B[0]) - ord('0'))
    print B[0], I
    B = B[1:]
I
1 1
1 3
0 6
1 13
13
s = 4
s << 1
8
'{0:.3f}'.format(5.561)
'5.561'

String Method: Changing String

S = 'xxxSPAMxxxSPAMxxx'
where = S.find('SPAM')
where
3
S = S[:where] + 'EGGS' + S[(where+4):]
S
'xxxEGGSxxxSPAMxxx'
S = 'xxxSPAMxxxSPAMxxx'
S.replace('SPAM', 'EGGS', 1) # replace one
'xxxEGGSxxxSPAMxxx'
S = 'spammy'
L = list(S)
L
['s', 'p', 'a', 'm', 'm', 'y']
L[4] = 'x'
L
['s', 'p', 'a', 'm', 'x', 'y']
S = ''.join(L)
S
'spamxy'
'SPAM'.join(['eggs', 'sausage', 'hamn'])
'eggsSPAMsausageSPAMhamn'

Parsing Text

line = 'aaa bbb ccc'
col1 = line[0:3]
col2 = line[8:]
col1
'aaa'
col2
'ccc'
cols = line.split()
cols
['aaa', 'bbb', 'ccc']
line = 'Aqwe gsdf EGHSDv sdvsd\n'
line.rstrip()
'Aqwe gsdf EGHSDv sdvsd'
line.upper()
'AQWE GSDF EGHSDV SDVSDn'
line.endswith('d\n')
True
line.startswith('QWE')
False
line.find('sdv') != -1
True
'sdv' in line
True
sub = 'd\n'
line.endswith(sub)
True
line[-len(sub):] == sub
True
# the old module string
import string
S = 'a+b+c'
y = string.replace(S, '+', 'spam')
y
'aspambspamc'

Formatting Expression Basics

'That is %d %s bird' % (1, 'dead')
'That is 1 dead bird'
# string substitution
s = 'asd'
'ciao %s!' % s
'ciao asd!'
'%d %s %g' % (1, 'spam', 4.0)
'1 spam 4'
'%s -- %s -- %s' % (42, 3.123, [1, 2, 3]) # all types match a %s target
'42 -- 3.123 -- [1, 2, 3]'

Advance Formatting

x = 1234
res = 'integer: ...%d...%-6d...%06d' % (x, x, x)
res
'integer: ...1234...1234  ...001234'
x = 1.234156451
x
1.234156451
'%e | %f | %.2f | %g' % (x ,x, x, x)
'1.234156e+00 | 1.234156 | 1.23 | 1.23416'
'%E' % x
'1.234156E+00'
'%g' % 123.123198765432 # default precision of 6 digits
'123.123'
'%-6.2f | %05.2f | %+06.1f | %-06.1f' % (x, x, x, x)
'1.23   | 01.23 | +001.2 | 1.2   '
'%s' % x, str(x)
('1.234156451', '1.234156451')
# if sizes are not know until runtime use *
'%f, %.2f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)
'0.333333, 0.33, 0.3333'

Dictionary based formatting exp

'%(qty)d more %(food)s' % {'qty': 2, 'food': 'gnocchi'}
'2 more gnocchi'
reply = """
Ciao!
Hello %(name)s!
Your age is %(age)s
"""
values = {'name': 'Emanuele', 'age': '25'}
print(reply % values)
Ciao!
Hello Emanuele!
Your age is 25
qty = 10
food = 'gnocchi'
'%(qty)d more %(food)s' % vars()
'10 more gnocchi'
'%o, %x, %x, %X' % (64, 64, 255, 64)
'100, 40, ff, 40'

String formatting Method Calls

template = '{0}, {1} and {2}'.format('a', 'b', 'c') # by position
template
'a, b and c'
templ = '{motto} {0} and {pork}' # by keywords and position
templ.format('ham', motto='pasta', pork='porco')
'pasta ham and porco'
templ = '{} {} {}' # be relative pos
templ.format('123', 'cioao', 'gdfg')
'123 cioao gdfg'
template = '%(motto)s, %(pork)s and %(food)s'
template % dict(motto='asd', pork='123', food='876')
'asd, 123 and 876'
X = '{motto} {0} and {food}'.format(42, motto=3.14, food=[1, 2])
X
'3.14 42 and [1, 2]'
X.split(' and ')
['3.14 42', '[1, 2]']
import sys
'My {1[kind]} runs {0.platform}'.format(sys, {'kind': 'laptop'})
'My laptop runs linux2'
'My {map[kind]} runs {sys.platform}'.format(sys=sys, map={'kind': 'laptop'})
'My laptop runs linux2'
somelist = list('SPAM')
somelist
['S', 'P', 'A', 'M']
'first={0[0]}, third={0[2]}'.format(somelist) # only positive offset work
'first=S, third=A'
'first={0}, last={1}'.format(somelist[0], somelist[-1])
'first=S, last=M'
parts = (somelist[0], somelist[1:3], somelist[-1])
'first={0}, middle={1}, last={2}'.format(*parts)
"first=S, middle=['P', 'A'], last=M"

Advanced formatting method syntax

'{0[kind]!s}'.format(dict(kind='test'))
'test'
'{0[kind]!s}'.format(dict(kind=1.12312)) # is like calling str
'1.12312'
'{0[kind]!r}'.format(dict(kind='test')) # is like calling repr
"'test'"
'{0[kind]:<,}'.format(dict(kind=12425612341))
'12,425,612,341'
'{0[kind]:<10,.4}'.format(dict(kind=3.12312341))
'3.123     '
'{0:10} = {1:10}'.format('spam', 123.456)
'spam       =    123.456'
'{0:>10} = {1:<10}'.format('spam', 123.3467)
'      spam = 123.3467  '
'{0.platform:>10} = {1[kind]:<10}'.format(sys, dict(kind='porco'))
'    linux2 = porco     '
# a less explicit way to format with method call
'{:10} = {:10}'.format('spamspam', 123.45678)
'spamspam   =  123.45678'
'{.platform:>10} = {[kind]:<10}'.format(sys, dict(kind='porco'))
'    linux2 = porco     '
'{0:e}, {1:.3e}, {2:g}'.format(3.123512, 3.123512, 3.123512)
'3.123512e+00, 3.124e+00, 3.12351'
'{0:f}, {1:.2f}, {2:06.2f}'.format(3.123512, 3.123512, 3.123512)
'3.123512, 3.12, 003.12'
'{0:X} {1:o} {2:b}'.format(255, 255, 255)
'FF 377 11111111'
bin(255), int('11111111', 2), 0b11111111 # binary from/to
('0b11111111', 255, 255)
hex(255), int('FF', 16), 0xFF # from/to hex
('0xff', 255, 255)
oct(255), int('377', 8), 0o377 # from/to octal
('0377', 255, 255)
'{0:.{1}f}'.format(2.124356, 3) # take parameter from arguments
'2.124'
'%.*f' % (3, 1 / 3.0)
'0.333'
'%s %s %s' % (3.14159, 42, [1, 2])
'3.14159 42 [1, 2]'
'My %(kind)s runs %(platform)s' % {'kind': 'computer', 'platform': sys.platform}
'My computer runs linux2'
'%(test)s' % dict(test='this is a test')
'this is a test'
'%-10s = %10s' % ('spam', 123.4567)
'spam       =   123.4567'
'%e, %.3e, %g' % (3.235123, 12.34231, 2.423412)
'3.235123e+00, 1.234e+01, 2.42341'
'%f, %.3f, %06.2f' % (3.14156, 3.14156, 3.14156)
'3.141560, 3.142, 003.14'
'%x, %o' % (255, 255) # there is not binary
'ff, 377'
'{1[kind]:<8}   {0.platform:>8}'.format(sys, {'kind':'laptop'})
'laptop       linux2'
'%(kind)-8s   %(plat)8s' % dict(kind='laptop', plat=sys.platform)
'laptop       linux2'
data = dict(platform=sys.platform, kind='laptop')
'{kind:<8} {platform:>8}'.format(**data)
'laptop     linux2'
'%(kind)-8s  %(platform)8s' % data
'laptop      linux2'
'{0:,d}'.format(999999999999999) # thousand separator
'999,999,999,999,999'