Python Basics (2023-12-18 - 2023-12-20)

[1]:
for i in range(5):
    print(i)
    print(i+2)
print('habe fertig')
0
2
1
3
2
4
3
5
4
6
habe fertig

was jetzt geschehen wird

[2]:
j = 42
[3]:
j
[3]:
42
[4]:
type(j)
[4]:
int
[5]:
try:
    a
except Exception as e:
    print(type(e), e)
<class 'NameError'> name 'a' is not defined
[6]:
type(j)
[6]:
int
[7]:
j = [1, 2, 3]
[8]:
type(j)
[8]:
list
[9]:
j = 42.45
[10]:
type(j)
[10]:
float
[11]:
translation_table = {
    'one': 1,
    'two': 2,
}
[12]:
translation_table['one']
[12]:
1
[13]:
2**1000
[13]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
[14]:
if 1 == '1':
    print('ja')
else:
    print('nein')
nein
[15]:
def max(a, b):
    '''
    das ist eine hochkomplexe blah
    blah
    bla

    '''
    return a + b
[16]:
max(1, 2)
[16]:
3
[17]:
max.__doc__
[17]:
'\n    das ist eine hochkomplexe blah\n    blah\n    bla\n\n    '
[18]:
help(max)
Help on function max in module __main__:

max(a, b)
    das ist eine hochkomplexe blah
    blah
    bla

[19]:
type(max)
[19]:
function
[20]:
type(j)
[20]:
float
[21]:
j = max
[22]:
type(j)
[22]:
function
[23]:
j(1, 2)
[23]:
3
[24]:
import sys
[25]:
sys.argv
[25]:
['/home/jfasch/venv/jfasch-home/lib64/python3.10/site-packages/ipykernel_launcher.py',
 '-f',
 '/home/jfasch/.local/share/jupyter/runtime/kernel-98f8b9be-ad8f-4023-81a2-d1dc67d0282c.json']
[26]:
sys.platform
[26]:
'linux'
[27]:
sys.path
[27]:
['/home/jfasch/work/jfasch-home/trainings/log/detail/2023-12-18--Python-Basics',
 '/usr/lib64/python310.zip',
 '/usr/lib64/python3.10',
 '/usr/lib64/python3.10/lib-dynload',
 '',
 '/home/jfasch/venv/jfasch-home/lib64/python3.10/site-packages',
 '/home/jfasch/venv/jfasch-home/lib/python3.10/site-packages',
 '/home/jfasch/venv/jfasch-home/lib64/python3.10/site-packages/IPython/extensions',
 '/home/jfasch/.ipython']
[28]:
type(sys)
[28]:
module
[29]:
sys = 666
[30]:
try:
    sys.argv
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> 'int' object has no attribute 'argv'

Variables

[31]:
a = 42
[32]:
type(a)
[32]:
int
[33]:
a = 1.5
[34]:
type(a)
[34]:
float
[35]:
a = ['blah', 1.5]
[36]:
type(a)
[36]:
list
[37]:
a, b, c = 1, 'eins', 1.0
[38]:
a
[38]:
1
[39]:
b
[39]:
'eins'
[40]:
c
[40]:
1.0
[41]:
a, b = 1, 2
[42]:
a
[42]:
1
[43]:
b
[43]:
2
[44]:
tmp = a
[45]:
a = b
[46]:
b = tmp
[47]:
a
[47]:
2
[48]:
b
[48]:
1
[49]:
a, b = 1, 2
[50]:
a, b = b, a
[51]:
a
[51]:
2
[52]:
b
[52]:
1
[53]:
(a, b) = (b, a)
[54]:
a = 42
[55]:
id(a)
[55]:
139783143835152
[56]:
hex(id(a))
[56]:
'0x7f21cca24610'
[57]:
b = a
[58]:
id(b)
[58]:
139783143835152
[59]:
id(a) == id(b)
[59]:
True
[60]:
a is b
[60]:
True

Datatypes

Integers

[61]:
i = 42
[62]:
i = -42
[63]:
i = 2**64-1
[64]:
bin(i)
[64]:
'0b1111111111111111111111111111111111111111111111111111111111111111'
[65]:
len(bin(i))
[65]:
66
[66]:
i += 1
[67]:
len(bin(i))
[67]:
67
[68]:
bin(i)
[68]:
'0b10000000000000000000000000000000000000000000000000000000000000000'
[69]:
i
[69]:
18446744073709551616
[70]:
i += 2**100
[71]:
bin(i)
[71]:
'0b10000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000'
[72]:
1_000_000
[72]:
1000000
[73]:
3/2
[73]:
1.5
[74]:
3//2
[74]:
1
[75]:
3//2
[75]:
1
[76]:
3%2
[76]:
1
[77]:
16/4
[77]:
4.0
[78]:
16%4
[78]:
0
[79]:
17%4
[79]:
1
[80]:
2**3
[80]:
8
[81]:
(3**2)-1
[81]:
8

Datatype Conversion

[82]:
i = 42
[83]:
j = 42.666
[84]:
i = j
[85]:
i
[85]:
42.666
[86]:
i = 42
[87]:
s = 'abc'
[88]:
type(s)
[88]:
str
[89]:
i
[89]:
42
[90]:
s = str(i)
[91]:
s
[91]:
'42'
[92]:
j = int(s)
[93]:
j
[93]:
42
[94]:
try:
    int('abc')
except Exception as e:
    print(type(e), e)
<class 'ValueError'> invalid literal for int() with base 10: 'abc'
[95]:
int('abc', 16)
[95]:
2748
[96]:
try:
    int('42.666')
except Exception as e:
    print(type(e), e)
<class 'ValueError'> invalid literal for int() with base 10: '42.666'
[97]:
float('42.666')
[97]:
42.666
[98]:
s = 'abc'
[99]:
if type(s) is str:
    print('jo')
jo
[100]:
d = {
    'one': 1,
    'two': 2,
    'three': 3,
}
[101]:
str(d)
[101]:
"{'one': 1, 'two': 2, 'three': 3}"
[102]:
int('12345', 7)
[102]:
3267

Compound Datatypes

List

[103]:
l = [1, 2, 3]
[104]:
l
[104]:
[1, 2, 3]
[105]:
len(l)
[105]:
3
[106]:
l.append('vier')
[107]:
l
[107]:
[1, 2, 3, 'vier']
[108]:
l.append(5.0)
[109]:
l
[109]:
[1, 2, 3, 'vier', 5.0]
[110]:
l.append([6, 7, 'acht'])
[111]:
len(l)
[111]:
6
[112]:
l
[112]:
[1, 2, 3, 'vier', 5.0, [6, 7, 'acht']]
[113]:
l.append(l)
[114]:
len(l)
[114]:
7
[115]:
l
[115]:
[1, 2, 3, 'vier', 5.0, [6, 7, 'acht'], [...]]
[116]:
l[0]
[116]:
1
[117]:
l[6]
[117]:
[1, 2, 3, 'vier', 5.0, [6, 7, 'acht'], [...]]
[118]:
l[-1]
[118]:
[1, 2, 3, 'vier', 5.0, [6, 7, 'acht'], [...]]
[119]:
l[-2]
[119]:
[6, 7, 'acht']
[120]:
l[4]
[120]:
5.0
[121]:
l[-3]
[121]:
5.0
[122]:
del l[-1]
[123]:
l
[123]:
[1, 2, 3, 'vier', 5.0, [6, 7, 'acht']]
[124]:
l.extend([10, 20, 30])
[125]:
l
[125]:
[1, 2, 3, 'vier', 5.0, [6, 7, 'acht'], 10, 20, 30]
[126]:
try:
    l.sort()
except Exception as e:
    print(type(e), e)
<class 'TypeError'> '<' not supported between instances of 'str' and 'int'
[127]:
l
[127]:
[1, 2, 3, 'vier', 5.0, [6, 7, 'acht'], 10, 20, 30]
[128]:
l1 = [1, 2, 3]
[129]:
l1.extend([4, 5, 6])
[130]:
l1
[130]:
[1, 2, 3, 4, 5, 6]
[131]:
l1.extend(l1)
[132]:
l1
[132]:
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
[133]:
l1.sort()
[134]:
l1
[134]:
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]
[135]:
l1 = [1,2,3]
[136]:
l1
[136]:
[1, 2, 3]
[137]:
l2 = [3, 4, [5, 6, 7]]
[138]:
l1.extend(l2)
[139]:
l1
[139]:
[1, 2, 3, 3, 4, [5, 6, 7]]
[140]:
l2[-1]
[140]:
[5, 6, 7]
[141]:
l2[-1].append(666)
[142]:
l2
[142]:
[3, 4, [5, 6, 7, 666]]
[143]:
l1
[143]:
[1, 2, 3, 3, 4, [5, 6, 7, 666]]
[144]:
l = [3, 1, 2, 4, 5, 88, 42]
[145]:
3 in l
[145]:
True
[146]:
2 in l
[146]:
True
[147]:
666 in l
[147]:
False

Tuple

[148]:
l = [1, 2, 3]
[149]:
id(l)
[149]:
139782834179584
[150]:
l.append(4)
[151]:
id(l)
[151]:
139782834179584
[152]:
i = 42
[153]:
id(i)
[153]:
139783143835152
[154]:
i += 1
[155]:
i
[155]:
43
[156]:
id(i)
[156]:
139783143835184
[157]:
t = (1, 2, 3)
[158]:
try:
    t.append(4)
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> 'tuple' object has no attribute 'append'
[159]:
t[1]
[159]:
2
[160]:
try:
    t[1] += 5
except Exception as e:
    print(type(e), e)
<class 'TypeError'> 'tuple' object does not support item assignment
[161]:
t = (1, 2, [3, 4])
[162]:
t[2]
[162]:
[3, 4]
[163]:
t[2].append(666)
[164]:
t
[164]:
(1, 2, [3, 4, 666])
[165]:
try:
    t[0] = 7
except Exception as e:
    print(type(e), e)
<class 'TypeError'> 'tuple' object does not support item assignment

Dictionary

[166]:
d = {
    'one': 1,
    'two': 2,
}
[167]:
d['one']
[167]:
1
[168]:
try:
    d['three']
except Exception as e:
    print(type(e), e)
<class 'KeyError'> 'three'
[169]:
d['three'] = 3
[170]:
'three' in d
[170]:
True
[171]:
d1 = {
    'three': 33,
    'four': 'vier'
}
[172]:
d.update(d1)
[173]:
d
[173]:
{'one': 1, 'two': 2, 'three': 33, 'four': 'vier'}
[174]:
d = {}
[175]:
type(d)
[175]:
dict
[176]:
d = dict()
[177]:
type(d)
[177]:
dict

Set

[178]:
menge = {1, 2, 3}
[179]:
menge.add(4)
[180]:
menge.add('fuenf')
[181]:
menge
[181]:
{1, 2, 3, 4, 'fuenf'}
[182]:
menge.remove(2)
[183]:
menge
[183]:
{1, 3, 4, 'fuenf'}
[184]:
4 in menge
[184]:
True
[185]:
menge.add(5)
[186]:
menge
[186]:
{1, 3, 4, 5, 'fuenf'}
[187]:
menge.remove(5)
[188]:
menge
[188]:
{1, 3, 4, 'fuenf'}
[189]:
m1 = {1, 2, 3, 4}
[190]:
m2 = {3, 4, 5, 6}
[191]:
m1 | m2
[191]:
{1, 2, 3, 4, 5, 6}
[192]:
m1 & m2
[192]:
{3, 4}
[193]:
m1 - m2
[193]:
{1, 2}
[194]:
m2 - m1
[194]:
{5, 6}
[195]:
type(m2)
[195]:
set
[196]:
3 in m1
[196]:
True
[197]:
leeres_set = set()

Boolean

[198]:
b = True
[199]:
type(b)
[199]:
bool
[200]:
i = 666
[201]:
bool(i)
[201]:
True
[202]:
bool(0)
[202]:
False
[203]:
bool('')
[203]:
False
[204]:
l = []
len(l)
[204]:
0
[205]:
bool(l)
[205]:
False
[206]:
l = None
[207]:
type(l)
[207]:
NoneType
[208]:
l = []
[209]:
if l:
    print('jo')
else:
    print('na')
na
[210]:
if len(l):
    print('jo')
else:
    print('na')
na
[211]:
if len(l) == 0:
    print('jo')
else:
    print('na')
jo

Weirdness (Comprehensions)

List Comprehension

[212]:
numbers = [0, 1, 2, 3, 4, 5]
[213]:
squares = []
for n in numbers:
    squares.append(n**2)
[214]:
squares
[214]:
[0, 1, 4, 9, 16, 25]
[215]:
[n**2 for n in numbers]
[215]:
[0, 1, 4, 9, 16, 25]

Dictionary Comprehension (Exchange key and Value of dict)

[216]:
d = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}
[217]:
for k in d.keys():
    print(d[k])
0
1
2
3
4
5
6
7
8
9
[218]:
for v in d.values():
    print(v)
0
1
2
3
4
5
6
7
8
9
[219]:
for item in d.items():
    print(item)
('zero', 0)
('one', 1)
('two', 2)
('three', 3)
('four', 4)
('five', 5)
('six', 6)
('seven', 7)
('eight', 8)
('nine', 9)
[220]:
for item in d.items():
    k = item[0]
    v = item[1]
    print(k, v)
zero 0
one 1
two 2
three 3
four 4
five 5
six 6
seven 7
eight 8
nine 9
[221]:
for k, v in d.items():
    print(k, v)
zero 0
one 1
two 2
three 3
four 4
five 5
six 6
seven 7
eight 8
nine 9
[222]:
d_reversed = {}
[223]:
for k, v in d.items():
    d_reversed[v] = k
[224]:
d_reversed
[224]:
{0: 'zero',
 1: 'one',
 2: 'two',
 3: 'three',
 4: 'four',
 5: 'five',
 6: 'six',
 7: 'seven',
 8: 'eight',
 9: 'nine'}
[225]:
d_reversed = {v:k for k, v in d.items()}
[226]:
d_reversed
[226]:
{0: 'zero',
 1: 'one',
 2: 'two',
 3: 'three',
 4: 'four',
 5: 'five',
 6: 'six',
 7: 'seven',
 8: 'eight',
 9: 'nine'}

Functional Programming

[227]:
l = [0, 1, 2, 3, 4, 5]
[228]:
def square(n):
    return n**2
[229]:
for s in map(square, l):
    print(s)
0
1
4
9
16
25
[230]:
for s in map(lambda n: n**2, l):
    print(s)
0
1
4
9
16
25
[231]:
for s in filter(lambda n: n%2==0, l):
    print(s)
0
2
4
[232]:
d
[232]:
{'zero': 0,
 'one': 1,
 'two': 2,
 'three': 3,
 'four': 4,
 'five': 5,
 'six': 6,
 'seven': 7,
 'eight': 8,
 'nine': 9}
[233]:
l1 = [1, 2, 3]
l2 = ['one', 'two', 'three']
[234]:
for elem in zip(l1, l2):
    print(elem)
(1, 'one')
(2, 'two')
(3, 'three')
[235]:
for elem in zip(d.keys(), d.values()):
    print(elem)
('zero', 0)
('one', 1)
('two', 2)
('three', 3)
('four', 4)
('five', 5)
('six', 6)
('seven', 7)
('eight', 8)
('nine', 9)
[236]:
for elem in zip(d.values(), d.keys()):
    print(elem)
(0, 'zero')
(1, 'one')
(2, 'two')
(3, 'three')
(4, 'four')
(5, 'five')
(6, 'six')
(7, 'seven')
(8, 'eight')
(9, 'nine')
[237]:
{v: k for v, k in zip(d.values(), d.keys())}
[237]:
{0: 'zero',
 1: 'one',
 2: 'two',
 3: 'three',
 4: 'four',
 5: 'five',
 6: 'six',
 7: 'seven',
 8: 'eight',
 9: 'nine'}
[238]:
l = [(1, 'one'), (2, 'two')]
[239]:
dict(l)
[239]:
{1: 'one', 2: 'two'}
[240]:
dict(zip(d.values(), d.keys()))
[240]:
{0: 'zero',
 1: 'one',
 2: 'two',
 3: 'three',
 4: 'four',
 5: 'five',
 6: 'six',
 7: 'seven',
 8: 'eight',
 9: 'nine'}

set(), list(), dict()

[241]:
l = [2, 4, 10, 9, 1]
[242]:
s = set(l)
[243]:
s
[243]:
{1, 2, 4, 9, 10}
[244]:
list(s)
[244]:
[1, 2, 4, 9, 10]
[245]:
s1 = {2, 3, 4}
s2 = {4, 5, 6}
[246]:
s1 - s2
[246]:
{2, 3}
[247]:
set(s1|s2)
[247]:
{2, 3, 4, 5, 6}
[248]:
set(s1 - s2)
[248]:
{2, 3}
[249]:
diff = s1 - s2
[250]:
diff
[250]:
{2, 3}
[251]:
set(diff)
[251]:
{2, 3}

while (and else)

Summe von 1..100 (beide inklusive)

[252]:
summe = 0
n = 1
while n <= 100:
    summe += n
    n += 1
print(summe)
5050
[253]:
sum(range(1, 101))     # <--- pythonic
[253]:
5050
[254]:
int(100*101/2)
[254]:
5050
[255]:
import random
[256]:
while True:
    eyes = random.randrange(1, 7)
    if eyes == 6:
        print('yaay')
        break
    else:
        print('lose', eyes)
lose 4
yaay
[257]:
n_tries = 0
while n_tries < 8:
    eyes = random.randrange(1, 7)
    if eyes == 6:
        print('yaay')
        break
    else:
        print('lose in versuch', n_tries, ',', eyes)
    n_tries += 1
else:
    print('kompletter lose')
lose in versuch 0 , 1
lose in versuch 1 , 3
lose in versuch 2 , 1
lose in versuch 3 , 1
lose in versuch 4 , 5
lose in versuch 5 , 3
lose in versuch 6 , 4
lose in versuch 7 , 3
kompletter lose

range()

[258]:
l = [0, 1, 2, 3, 4]
for elem in l:
    print(elem)
0
1
2
3
4
[259]:
for elem in l:
    print('hallo')
hallo
hallo
hallo
hallo
hallo
[260]:
for elem in range(5):
    print(elem)
0
1
2
3
4
[261]:
for elem in range(2, 10):
    print(elem)
2
3
4
5
6
7
8
9
[262]:
for elem in range(2, 10, 2):
    print(elem)
2
4
6
8

range(), And Generators, The Iterator Protocol

[263]:
l = [0, 1, 2, 3, 4]
for elem in l:
    print(elem)
0
1
2
3
4
[264]:
print(type(l))
<class 'list'>
[265]:
r = range(5)
for elem in r:
    print(elem)
0
1
2
3
4
[266]:
r
[266]:
range(0, 5)
[267]:
print(type(r))
<class 'range'>
[268]:
for elem in r:
    print(elem)
0
1
2
3
4
[269]:
for elem in l:
    print(elem)
0
1
2
3
4
[270]:
it = iter(l)
[271]:
print(type(it))
<class 'list_iterator'>
[272]:
next(it)
[272]:
0
[273]:
next(it)
[273]:
1
[274]:
next(it)
[274]:
2
[275]:
next(it)
[275]:
3
[276]:
next(it)
[276]:
4
[277]:
try:
    next(it)
except Exception as e:
    print(type(e), e)
<class 'StopIteration'>
[278]:
r = range(3)
[279]:
it = iter(r)
[280]:
next(it)
[280]:
0
[281]:
def foo(bar):
    return bar**2
[282]:
def my_deppertes_range():
    print('start')
    yield 0
    print('yield 1')
    yield 1
    print('yield 2')
    yield 2
    print('end')
[283]:
mdr = my_deppertes_range()
for elem in mdr:
    print('got', elem)
start
got 0
yield 1
got 1
yield 2
got 2
end
[284]:
mdr = my_deppertes_range()
[285]:
it = iter(mdr)
[286]:
next(it)
start
[286]:
0
[287]:
next(it)
yield 1
[287]:
1
[288]:
next(it)
yield 2
[288]:
2
[289]:
try:
    next(it)
except Exception as e:
    print(type(e), e)
end
<class 'StopIteration'>
[290]:
numbers = range(20)
[291]:
def even(seq):
    for n in seq:
        if n%2 == 0:
            yield n
[292]:
for elem in even(numbers):
    print(elem)
0
2
4
6
8
10
12
14
16
18

Functions

[293]:
def maximum(a, b):
    '''
    blah

    * a: links
    * b: rechts
    '''

    if a < b:
        return b
    return a
[294]:
maximum(1, 2)
[294]:
2
[295]:
maximum('aaa', 'bbb')
[295]:
'bbb'
[296]:
i = 666
print(type(i))
<class 'int'>
[297]:
print(type(maximum))
<class 'function'>
[298]:
i = maximum
[299]:
i(1, 2)
[299]:
2

Return Value? Parameters?

[300]:
def foo():
    return True
[301]:
x = foo()
[302]:
x
[302]:
True
[303]:
if foo():
    print('ja')
else:
    print('nein')
ja
[304]:
def foo():
    return False
[305]:
if foo():
    print('ja')
else:
    print('nein')
nein
[306]:
def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False
[307]:
if is_even(9):
    print('ja')
else:
    print('nein')
nein
[308]:
is_even(10)
[308]:
True

More About Datatypes

References, Immutability

Integer objeckte sind Singletons bis 256 (?)

[309]:
a = 42
[310]:
id(a)
[310]:
139783143835152
[311]:
b = 42
[312]:
id(b)
[312]:
139783143835152
[313]:
l1 = [1, 2, 3]
[314]:
id(l1)
[314]:
139782799029888
[315]:
l2 = [1, 2, 3]
[316]:
id(l2)
[316]:
139782798781696
[317]:
a = 666
[318]:
id(a)
[318]:
139782798895952
[319]:
b = 666
[320]:
id(b)
[320]:
139782798895792
[321]:
a = 42
[322]:
id(a)
[322]:
139783143835152
[323]:
a += 1
[324]:
id(a)
[324]:
139783143835184
[325]:
def foo(n):
    n += 1
[326]:
a
[326]:
43
[327]:
foo(a)
[328]:
a
[328]:
43
[329]:
l = [1,2,3]
[330]:
def foo(seq):
    seq.append(666)
[331]:
foo(l)
[332]:
l
[332]:
[1, 2, 3, 666]
[333]:
t = (1,2,3)
[334]:
try:
    foo(t)
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> 'tuple' object has no attribute 'append'

Und Schuetzen?

[335]:
l1 = [1, 2, 3]
def avg(seq):
    rv = sum(seq)/len(seq)
    seq.append(666)
    return rv
[336]:
avg(l1)
[336]:
2.0
[337]:
l1
[337]:
[1, 2, 3, 666]
[338]:
l1 = [1, 2, 3]
[339]:
id(l1)
[339]:
139782798980096
[340]:
l1_copy = l1[:]
[341]:
avg(l1_copy)
[341]:
2.0
[342]:
l1 = [1, 2, ['abc', 'def'], 3, 4]
[343]:
l2 = l1[:]
[344]:
l1 is l2
[344]:
False
[345]:
l2.append(666)
[346]:
l1
[346]:
[1, 2, ['abc', 'def'], 3, 4]
[347]:
l2
[347]:
[1, 2, ['abc', 'def'], 3, 4, 666]
[348]:
l2[2].append('ghi')
[349]:
l2
[349]:
[1, 2, ['abc', 'def', 'ghi'], 3, 4, 666]
[350]:
l1
[350]:
[1, 2, ['abc', 'def', 'ghi'], 3, 4]
[351]:
t1 = (1, 2, ['abc', 'def'], 3, 4)
[352]:
t2 = t1[:4]
[353]:
t1 is t2
[353]:
False
[354]:
t1[2] is t2[2]
[354]:
True
[355]:
t2[2].append('teifl')
[356]:
t1
[356]:
(1, 2, ['abc', 'def', 'teifl'], 3, 4)

More About Strings

[357]:
s = 'blah'
[358]:
s
[358]:
'blah'
[359]:
s = "blah"
[360]:
s
[360]:
'blah'
[361]:
'Es ist Joerg\'s Schuld'
[361]:
"Es ist Joerg's Schuld"
[362]:
"Es ist Joerg's Schuld"
[362]:
"Es ist Joerg's Schuld"
[363]:
"erste zeile\nzweite zeile"
[363]:
'erste zeile\nzweite zeile'
[364]:
print("erste zeile\nzweite zeile")
erste zeile
zweite zeile
[365]:
print("a\tb")
a       b
[366]:
print("a\\b")
a\b
[367]:
dos_path = "C:\Programs\Meine Programme\neues programm"
[368]:
print(dos_path)
C:\Programs\Meine Programme
eues programm
[369]:
dos_path = "C:\Programs\Meine Programme\\neues programm"
[370]:
print(dos_path)
C:\Programs\Meine Programme\neues programm
[371]:
dos_path = r"C:\Programs\Meine Programme\neues programm"
[372]:
print(dos_path)
C:\Programs\Meine Programme\neues programm

Formatting

[373]:
"blah %d blah" % 666
[373]:
'blah 666 blah'
[374]:
"blah %d blah %.6f" % (666, 42.3)
[374]:
'blah 666 blah 42.300000'
[375]:
'blah {0} blah {1} blah {0}'.format(666, 42.3)
[375]:
'blah 666 blah 42.3 blah 666'
[376]:
'blah {a} blah {b} blah {a}'.format(b=666, a=42.3)
[376]:
'blah 42.3 blah 666 blah 42.3'
[377]:
a, b = 42.3, 666
[378]:
f'blah {a} blah {b} {a}'
[378]:
'blah 42.3 blah 666 42.3'
[379]:
f'blah {a+1}'
[379]:
'blah 43.3'
[380]:
f'blah {[i**2 for i in range(5)]}'
[380]:
'blah [0, 1, 4, 9, 16]'

Regular Expressions

[381]:
line = '     666         ; Joerg     ;Faschingbauer      '
[382]:
pattern = r'^\s*(\d+)\s*;\s*([A-Za-z]+)\s*;\s*([A-Za-z]+)\s*$'
[383]:
print(pattern)
^\s*(\d+)\s*;\s*([A-Za-z]+)\s*;\s*([A-Za-z]+)\s*$
[384]:
import re
[385]:
compiled_pattern = re.compile(pattern)
[386]:
match = compiled_pattern.search(line)
[387]:
match.group(1)
[387]:
'666'
[388]:
match.group(2)
[388]:
'Joerg'
[389]:
match.group(3)
[389]:
'Faschingbauer'

Das gleich ohne regex

[390]:
line.split(';')
[390]:
['     666         ', ' Joerg     ', 'Faschingbauer      ']
[391]:
fields = []
for field in line.split(';'):
    fields.append(field.strip())
fields
[391]:
['666', 'Joerg', 'Faschingbauer']
[392]:
[field.strip() for field in line.split(';')]
[392]:
['666', 'Joerg', 'Faschingbauer']

Miscellaneous String Methods

[393]:
s = '      '
s.isspace()
[393]:
True
[394]:
'XXX'.isupper()
[394]:
True
[395]:
'xxx'.islower()
[395]:
True
[396]:
'666'.isdigit()
[396]:
True
[397]:
len('')
[397]:
0
[398]:
s = 'xxx'
[399]:
if len(s):
    print('was drin')
was drin
[400]:
if s:
    print('was drin')
was drin
[401]:
s = ''
[402]:
if s:
    print('was drin')
else:
    print('nix drin')
nix drin
[403]:
s = 'mississippi'
[404]:
s.count('ss')
[404]:
2
[405]:
s.upper()
[405]:
'MISSISSIPPI'
[406]:
s.find('ss')
[406]:
2
[407]:
s.find('ss', 2+1)
[407]:
5
[408]:
s.find('xxx')
[408]:
-1
[409]:
s.index('ss')
[409]:
2
[410]:
try:
    s.index('xxx')
except Exception as e:
    print(type(e), e)
<class 'ValueError'> substring not found
[411]:
filename = 'data.csv'
[412]:
filename.endswith('.csv')
[412]:
True
[413]:
line
[413]:
'     666         ; Joerg     ;Faschingbauer      '
[414]:
line.split(';')
[414]:
['     666         ', ' Joerg     ', 'Faschingbauer      ']
[415]:
items = ['666', 'Joerg', 'Faschingbauer']
[416]:
';'.join(items)
[416]:
'666;Joerg;Faschingbauer'
[417]:
'hallo'.center(80)
[417]:
'                                     hallo                                      '
[418]:
s = 'hallo'
' '*(80-len(s)) + s
[418]:
'                                                                           hallo'

More About Lists

[419]:
l = [1, 'two', 3.0]
[420]:
l.append(666)
[421]:
l
[421]:
[1, 'two', 3.0, 666]
[422]:
l1 = [8, 'neun']
[423]:
l.extend(l1)
l
[423]:
[1, 'two', 3.0, 666, 8, 'neun']
[424]:
del l[3]
[425]:
l
[425]:
[1, 'two', 3.0, 8, 'neun']
[427]:
l[2]
[427]:
3.0
[428]:
l.insert(0, -1)
[429]:
l
[429]:
[-1, 1, 'two', 3.0, 8, 'neun']
[430]:
l.insert(2, 1.5)
l
[430]:
[-1, 1, 1.5, 'two', 3.0, 8, 'neun']
[431]:
l.reverse()
l
[431]:
['neun', 8, 3.0, 'two', 1.5, 1, -1]
[434]:
for elem in reversed(l):
    print(elem)
-1
1
1.5
two
3.0
8
neun
[436]:
l.pop(5)
[436]:
1
[437]:
l
[437]:
['neun', 8, 3.0, 'two', 1.5, -1]

More About Dictionaries

[438]:
d = dict()
[439]:
d
[439]:
{}
[440]:
d = {'one': 1, 'two': 2}
[441]:
d = {}
[443]:
l = [('one', 1), ('two', 2)]
d = dict(l)
[444]:
d
[444]:
{'one': 1, 'two': 2}
[445]:
d['one']
[445]:
1
[447]:
try:
    d['three']
except Exception as e:
    print(type(e), e)
<class 'KeyError'> 'three'
[448]:
v = d.get('two')
v
[448]:
2
[449]:
v = d.get('three')
print(v)
None
[450]:
if d.get('three'):
    print('ja')
else:
    print('nein')
nein
[451]:
d['three'] = 3
[452]:
del d['three']
[453]:
d['three'] = None
[454]:
'three' in d
[454]:
True
[455]:
del d['three']
[456]:
v = d.get('three')
if v is None:
    v = 3
v
[456]:
3
[458]:
v = d.get('three', 3)
v
[458]:
3
[463]:
v = d.get('three')
if v is None:
    d['three'] = 3
    v = d['three']
v
[463]:
3
[464]:
del d['three']
[465]:
v = d.setdefault('three', 3)
v
[465]:
3
[467]:
d
[467]:
{'one': 1, 'two': 2, 'three': 3}
[468]:
for elem in d:
    print(elem)
one
two
three
[469]:
for elem in d.keys():
    print(elem)
one
two
three
[470]:
for elem in d.values():
    print(elem)
1
2
3
[471]:
for elem in d.items():
    print(elem)
('one', 1)
('two', 2)
('three', 3)
[472]:
for elem in d.items():
    k = elem[0]
    v = elem[1]
    print(k, v)
one 1
two 2
three 3
[473]:
for k, v in d.items():
    print(k, v)
one 1
two 2
three 3
[474]:
a, b = 1, 2
[475]:
a
[475]:
1
[476]:
b
[476]:
2
[477]:
(a, b) = (b, a)
[479]:
a
[479]:
2
[480]:
b
[480]:
1
[481]:
line = '666;Joerg;Faschingbauer'
id, firstname, lastname = line.split(';')
[483]:
id
[483]:
'666'
[486]:
try:
    id(a)
except Exception as e:
    print(type(e), e)
<class 'TypeError'> 'str' object is not callable
[487]:
int('666')
[487]:
666
[488]:
int = 666
[490]:
try:
    int('666')
except Exception as e:
    print(type(e), e)
<class 'TypeError'> 'int' object is not callable
[491]:
del int
[492]:
a = 666
[493]:
type(a)
[493]:
int
[494]:
int = type(a)
[497]:
int('666')
[497]:
666
[498]:
__builtins__
[498]:
<module 'builtins' (built-in)>
[499]:
__builtin__.id
[499]:
<function id(obj, /)>
[500]:
id = __builtins__.id
[501]:
id(a)
[501]:
139782799135312
[502]:
keys = [2, 3, 1, 5, 1]
dict.fromkeys(keys)
[502]:
{2: None, 3: None, 1: None, 5: None}
[503]:
for k in dict.fromkeys(keys):
    print(k)
2
3
1
5

More About Sets

[505]:
s = set('abc')
s
[505]:
{'a', 'b', 'c'}
[506]:
for elem in 'abc':
    print(elem)
a
b
c
[508]:
set(['abc', 'def'])
[508]:
{'abc', 'def'}
[510]:
try:
    set(666)
except Exception as e:
    print(type(e), e)
<class 'TypeError'> 'int' object is not iterable

Comprehensions (Generator Expressions)

[511]:
def squares(l):
    sqs = []
    for elem in l:
        sqs.append(elem**2)
    return sqs
[512]:
for elem in squares(range(5)):
    print(elem)
0
1
4
9
16
[513]:
for elem in [i**2 for i in range(5)]:
    print(elem)
0
1
4
9
16
[514]:
def squares(l):
    for elem in l:
        yield elem**2
[515]:
for elem in squares(range(5)):
    print(elem)
0
1
4
9
16
[517]:
for elem in (i**2 for i in range(5)):
    print(elem)
0
1
4
9
16
[518]:
(i**2 for i in range(5))
[518]:
<generator object <genexpr> at 0x7f21b81bbe60>
[519]:
[i**2 for i in range(5)]
[519]:
[0, 1, 4, 9, 16]

File I/O

[525]:
import os
[527]:
cwd = os.getcwd()
[529]:
os.chdir('/etc')
[533]:
os.getcwd()
[533]:
'/etc'
[534]:
os.listdir()
[534]:
['extlinux.conf',
 'favicon.png',
 'grub2-efi.cfg',
 'grub2.cfg',
 'issue',
 'issue.net',
 'opensc-x86_64.conf',
 '.java',
 'NetworkManager',
 'PackageKit',
 'UPower',
 'X11',
 'abrt',
 'alsa',
 'alternatives',
 'anaconda',
 'audit',
 'authselect',
 'avahi',
 'bash_completion.d',
 'binfmt.d',
 'bluetooth',
 'brltty',
 'ceph',
 'chkconfig.d',
 'chromium',
 'cifs-utils',
 'containers',
 'crypto-policies',
 'cups',
 'cupshelpers',
 'dbus-1',
 'dconf',
 'debuginfod',
 'default',
 'depmod.d',
 'dhcp',
 'dnf',
 'dnsmasq.d',
 'dracut.conf.d',
 'egl',
 'exports.d',
 'firefox',
 'firewalld',
 'flatpak',
 'flexiblasrc.d',
 'fonts',
 'fwupd',
 'gcrypt',
 'gdbinit.d',
 'gdm',
 'geoclue',
 'glvnd',
 'gnupg',
 'groff',
 'grub.d',
 'gss',
 'gssproxy',
 'hp',
 'httpd',
 'iproute2',
 'iscsi',
 'issue.d',
 'java',
 'jvm-common',
 'jvm',
 'kdump',
 'kernel',
 'krb5.conf.d',
 'ld.so.conf.d',
 'libblockdev',
 'libibverbs.d',
 'libnl',
 'libpaper.d',
 'libreport',
 'libssh',
 'libvirt',
 'logrotate.d',
 'lvm',
 'mcelog',
 'mdevctl.d',
 'modprobe.d',
 'modules-load.d',
 'motd.d',
 'my.cnf.d',
 'ndctl.conf.d',
 'ndctl',
 'nftables',
 'openldap',
 'openvpn',
 'opt',
 'ostree',
 'pam.d',
 'pkcs11',
 'pkgconfig',
 'pki',
 'plymouth',
 'pm',
 'polkit-1',
 'popt.d',
 'ppp',
 'profile.d',
 'pulse',
 'qemu-ga',
 'qemu',
 'rc.d',
 'reader.conf.d',
 'request-key.d',
 'rpm',
 'rwtab.d',
 'samba',
 'sane.d',
 'sasl2',
 'security',
 'selinux',
 'sgml',
 'skel',
 'sos',
 'speech-dispatcher',
 'ssh',
 'ssl',
 'sssd',
 'statetab.d',
 'sudoers.d',
 'swid',
 'sysconfig',
 'sysctl.d',
 'systemd',
 'terminfo',
 'thermald',
 'tmpfiles.d',
 'tpm2-tss',
 'udev',
 'udisks2',
 'unbound',
 'vmware-tools',
 'vpnc',
 'vulkan',
 'wireplumber',
 'wpa_supplicant',
 'xdg',
 'xml',
 'yum.repos.d',
 'zfs-fuse',
 '.pwd.lock',
 'DIR_COLORS',
 'DIR_COLORS.lightbgcolor',
 'GREP_COLORS',
 'adjtime',
 'bindresvport.blacklist',
 'brlapi.key',
 'chrony.conf',
 'chrony.keys',
 'dleyna-renderer-service.conf',
 'dleyna-server-service.conf',
 'dracut.conf',
 'fprintd.conf',
 'fstab',
 'fuse.conf',
 'jwhois.conf',
 'libaudit.conf',
 'libuser.conf',
 'locale.conf',
 'login.defs',
 'magic',
 'mailcap',
 'man_db.conf',
 'mime.types',
 'mke2fs.conf',
 'nanorc',
 'netconfig',
 'papersize',
 'passwdqc.conf',
 'pinforc',
 'request-key.conf',
 'sestatus.conf',
 'shells',
 'sudoers',
 'tcsd.conf',
 'usb_modeswitch.conf',
 'vconsole.conf',
 'wgetrc',
 'xattr.conf',
 'crypttab',
 'machine-id',
 'machine-info',
 'localtime',
 'hostname',
 'mtab',
 'subuid-',
 'subgid-',
 'timidity.cfg',
 'timidity++.cfg',
 'openal',
 'vdpau_wrapper.cfg',
 'ld.so.conf',
 'rpc',
 'asound.conf',
 'krb5.conf',
 'idmapd.conf',
 'sysctl.conf',
 'logrotate.conf',
 'mtools.conf',
 'brltty.conf',
 'flexiblasrc',
 'ts.conf',
 'gdbinit',
 'rsyncd.conf',
 'anthy-unicode.conf',
 'kdump.conf',
 'Trolltech.conf',
 'my.cnf',
 'rygel.conf',
 'virc',
 'swtpm-localca.conf',
 'swtpm-localca.options',
 'swtpm_setup.conf',
 'uresourced.conf',
 'opensc.conf',
 'aliases',
 'environment',
 'ethertypes',
 'exports',
 'filesystems',
 'host.conf',
 'inputrc',
 'motd',
 'networks',
 'printcap',
 'profile',
 'protocols',
 'services',
 'csh.login',
 'hosts',
 'nfsmount.conf',
 'nfs.conf',
 'dnsmasq.conf',
 'resolv.conf',
 'nsswitch.conf',
 'group-',
 'gshadow-',
 'passwd-',
 'shadow-',
 'thunderbird',
 'rhashrc',
 'ImageMagick-6',
 'bashrc',
 'csh.cshrc',
 'gimp',
 'updatedb.conf',
 '.updated',
 'mplayer',
 'youtube-dl.conf',
 'appstream.conf',
 'mosquitto',
 'containerd',
 'docker',
 'at.deny',
 'lftp.conf',
 'shadow',
 'group',
 'gshadow',
 'subuid',
 'subgid',
 'passwd~',
 'passwd',
 'init.d',
 'rc0.d',
 'rc1.d',
 'rc2.d',
 'rc3.d',
 'rc4.d',
 'rc5.d',
 'rc6.d',
 'fedora-release',
 'os-release',
 'redhat-release',
 'system-release',
 'system-release-cpe',
 'inittab',
 'sudo.conf',
 'trusted-key.key',
 'makedumpfile.conf.sample',
 'sensors.d',
 'sensors3.conf',
 'ld.so.cache']
[531]:
f = open('passwd', encoding='utf-8')
[535]:
f
[535]:
<_io.TextIOWrapper name='passwd' mode='r' encoding='utf-8'>
[537]:
os.chdir(cwd)
[538]:
os.getcwd()
[538]:
'/home/jfasch/work/jfasch-home/trainings/log/detail/2023-12-18--Python-Basics'
[539]:
f = open('/etc/passwd', encoding='utf-8')
[541]:
f
[541]:
<_io.TextIOWrapper name='/etc/passwd' mode='r' encoding='utf-8'>
[542]:
f.read(5)
[542]:
'root:'
[544]:
f.read(5)
[544]:
':root'
[545]:
f.readline()
[545]:
':/root:/bin/bash\n'
[546]:
f.readline()
[546]:
'bin:x:1:1:bin:/bin:/sbin/nologin\n'
[547]:
f.read()
[547]:
'daemon:x:2:2:daemon:/sbin:/sbin/nologin\nadm:x:3:4:adm:/var/adm:/sbin/nologin\nlp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\nsync:x:5:0:sync:/sbin:/bin/sync\nshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\nhalt:x:7:0:halt:/sbin:/sbin/halt\nmail:x:8:12:mail:/var/spool/mail:/sbin/nologin\noperator:x:11:0:operator:/root:/sbin/nologin\ngames:x:12:100:games:/usr/games:/sbin/nologin\nftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\nnobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin\ndbus:x:81:81:System message bus:/:/sbin/nologin\napache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin\ntss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin\nsystemd-network:x:192:192:systemd Network Management:/:/usr/sbin/nologin\nsystemd-oom:x:999:999:systemd Userspace OOM Killer:/:/usr/sbin/nologin\nsystemd-resolve:x:193:193:systemd Resolver:/:/usr/sbin/nologin\nqemu:x:107:107:qemu user:/:/sbin/nologin\npolkitd:x:998:997:User for polkitd:/:/sbin/nologin\navahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin\nunbound:x:997:995:Unbound DNS resolver:/etc/unbound:/sbin/nologin\nnm-openconnect:x:996:994:NetworkManager user for OpenConnect:/:/sbin/nologin\ngeoclue:x:995:993:User for geoclue:/var/lib/geoclue:/sbin/nologin\nusbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin\ngluster:x:994:992:GlusterFS daemons:/run/gluster:/sbin/nologin\nrtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin\nchrony:x:993:990::/var/lib/chrony:/sbin/nologin\nsaslauth:x:992:76:Saslauthd user:/run/saslauthd:/sbin/nologin\ndnsmasq:x:991:989:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin\nrpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin\ncolord:x:990:988:User for colord:/var/lib/colord:/sbin/nologin\nrpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin\nopenvpn:x:989:987:OpenVPN:/etc/openvpn:/sbin/nologin\nnm-openvpn:x:988:986:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin\npipewire:x:987:985:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin\nabrt:x:173:173::/etc/abrt:/sbin/nologin\nflatpak:x:986:983:User for flatpak system helper:/:/sbin/nologin\ngdm:x:42:42:GNOME Display Manager:/var/lib/gdm:/sbin/nologin\ngnome-initial-setup:x:985:982::/run/gnome-initial-setup/:/sbin/nologin\nvboxadd:x:984:1::/var/run/vboxadd:/sbin/nologin\nsshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin\ntcpdump:x:72:72::/:/sbin/nologin\njfasch:x:1000:1000:Jörg Faschingbauer:/home/jfasch:/bin/bash\nsystemd-coredump:x:978:978:systemd Core Dumper:/:/usr/sbin/nologin\nsystemd-timesync:x:977:977:systemd Time Synchronization:/:/usr/sbin/nologin\nmosquitto:x:976:976:Mosquitto Broker:/etc/mosquitto:/sbin/nologin\n'
[548]:
f.read()
[548]:
''
[549]:
f.seek(0)
[549]:
0
[550]:
f.read(5)
[550]:
'root:'
[552]:
f = open('/etc/passwd', encoding='utf-8')
[553]:
for line in f:
    print(line)
root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/sbin/nologin

daemon:x:2:2:daemon:/sbin:/sbin/nologin

adm:x:3:4:adm:/var/adm:/sbin/nologin

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

sync:x:5:0:sync:/sbin:/bin/sync

shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

operator:x:11:0:operator:/root:/sbin/nologin

games:x:12:100:games:/usr/games:/sbin/nologin

ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin

nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin

dbus:x:81:81:System message bus:/:/sbin/nologin

apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin

tss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin

systemd-network:x:192:192:systemd Network Management:/:/usr/sbin/nologin

systemd-oom:x:999:999:systemd Userspace OOM Killer:/:/usr/sbin/nologin

systemd-resolve:x:193:193:systemd Resolver:/:/usr/sbin/nologin

qemu:x:107:107:qemu user:/:/sbin/nologin

polkitd:x:998:997:User for polkitd:/:/sbin/nologin

avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin

unbound:x:997:995:Unbound DNS resolver:/etc/unbound:/sbin/nologin

nm-openconnect:x:996:994:NetworkManager user for OpenConnect:/:/sbin/nologin

geoclue:x:995:993:User for geoclue:/var/lib/geoclue:/sbin/nologin

usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin

gluster:x:994:992:GlusterFS daemons:/run/gluster:/sbin/nologin

rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin

chrony:x:993:990::/var/lib/chrony:/sbin/nologin

saslauth:x:992:76:Saslauthd user:/run/saslauthd:/sbin/nologin

dnsmasq:x:991:989:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin

rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin

colord:x:990:988:User for colord:/var/lib/colord:/sbin/nologin

rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin

openvpn:x:989:987:OpenVPN:/etc/openvpn:/sbin/nologin

nm-openvpn:x:988:986:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin

pipewire:x:987:985:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin

abrt:x:173:173::/etc/abrt:/sbin/nologin

flatpak:x:986:983:User for flatpak system helper:/:/sbin/nologin

gdm:x:42:42:GNOME Display Manager:/var/lib/gdm:/sbin/nologin

gnome-initial-setup:x:985:982::/run/gnome-initial-setup/:/sbin/nologin

vboxadd:x:984:1::/var/run/vboxadd:/sbin/nologin

sshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin

tcpdump:x:72:72::/:/sbin/nologin

jfasch:x:1000:1000:Jörg Faschingbauer:/home/jfasch:/bin/bash

systemd-coredump:x:978:978:systemd Core Dumper:/:/usr/sbin/nologin

systemd-timesync:x:977:977:systemd Time Synchronization:/:/usr/sbin/nologin

mosquitto:x:976:976:Mosquitto Broker:/etc/mosquitto:/sbin/nologin

[557]:
f = open('/etc/passwd', encoding='ascii')
[558]:
try:
    for line in f:
        print(line)
except Exception as e:
    print(type(e), e)
<class 'UnicodeDecodeError'> 'ascii' codec can't decode byte 0xc3 in position 2440: ordinal not in range(128)

pathlib, os.path

[559]:
directory = '/etc'
filename = 'passwd'
[561]:
directory + '/' + filename
[561]:
'/etc/passwd'
[562]:
directory + os.sep + filename
[562]:
'/etc/passwd'
[563]:
os.path.join(directory, filename)
[563]:
'/etc/passwd'
[564]:
import pathlib
[565]:
directory = pathlib.Path('/etc')
[567]:
directory
[567]:
PosixPath('/etc')
[569]:
directory / filename
[569]:
PosixPath('/etc/passwd')

Regexen

[574]:
import re
[575]:
rex = r'[^A-F]'
[577]:
re.search(rex, 'X')
[577]:
<re.Match object; span=(0, 1), match='X'>
[578]:
re.search(rex, 'D')
[579]:
rex = r'^\s*(#.*|$)'
[580]:
re.search(rex, '       # xxx')
[580]:
<re.Match object; span=(0, 12), match='       # xxx'>
[581]:
re.search(rex, '        ')
[581]:
<re.Match object; span=(0, 8), match='        '>
[582]:
re.search(rex, '     kadjckk  # xxddjh')

distill.py

[585]:
s = ' \t   abc  \n   \n'
s.strip()
[585]:
'abc'
[588]:
s = '        # blah    '
s.strip()
[588]:
'# blah'
[589]:
print('blah')
blah
[590]:
print('blah\n')
blah

[593]:
print('blah', end='blahblah')
print('blah')
blahblahblahblah
[595]:
print('blah', end='')
print('blah')
blahblah