Compound Datatypes¶
Dictionary¶
[1]:
d = {}
[2]:
len(d)
[2]:
0
[3]:
d = {
11: 'Simmering',
1: 'Innere Stadt',
}
[4]:
len(d)
[4]:
2
[5]:
d[11]
[5]:
'Simmering'
[6]:
d[5] = 'Keine Ahnung'
len(d)
[6]:
3
[7]:
d[5]
[7]:
'Keine Ahnung'
[8]:
11 in d
[8]:
True
[9]:
'Simmering' in d
[9]:
False
Iteration¶
[95]:
d
[95]:
{11: 'Simmering', 1: 'Innere Stadt', 5: 'Keine Ahnung'}
[112]:
for element in d:
print(element)
11
1
5
[114]:
for key in d.keys():
print(key)
11
1
5
[116]:
for value in d.values():
print(value)
Simmering
Innere Stadt
Keine Ahnung
[118]:
for item in d.items():
print(item)
(11, 'Simmering')
(1, 'Innere Stadt')
(5, 'Keine Ahnung')
[120]:
for item in d.items():
key = item[0]
value = item [1]
print(f'key: {key}, value: {value}')
key: 11, value: Simmering
key: 1, value: Innere Stadt
key: 5, value: Keine Ahnung
[121]:
for key, value in d.items():
print(f'key: {key}, value: {value}')
key: 11, value: Simmering
key: 1, value: Innere Stadt
key: 5, value: Keine Ahnung
Set¶
[98]:
s = set()
len(s)
[98]:
0
[99]:
s.add(1)
s.add('Joerg')
len(s)
[99]:
2
[100]:
'Joerg' in s
[100]:
True
[101]:
'Christopher' in s
[101]:
False
[102]:
s.remove('Joerg')
[103]:
'Joerg' in s
[103]:
False
Iteration¶
[106]:
s = { 1, 2, 3, 4, 5}
[108]:
s
[108]:
{1, 2, 3, 4, 5}
[110]:
for element in s:
print(element)
1
2
3
4
5
List¶
[17]:
l = [1, 2, 3, 'vier']
[18]:
len(l)
[18]:
4
[19]:
1 in l
[19]:
True
[20]:
3 in l
[20]:
True
[21]:
'vier' in l
[21]:
True
Iterable?¶
[22]:
l = [1, 2, 3, 'vier']
for element in l:
print(element)
1
2
3
vier
[23]:
s = set(l)
s
[23]:
{1, 2, 3, 'vier'}
[24]:
mein_string = 'joerg'
for element in mein_string:
print(element)
j
o
e
r
g
[25]:
s = set(mein_string)
s
[25]:
{'e', 'g', 'j', 'o', 'r'}
[26]:
for element in s:
print(element)
g
j
e
o
r
[27]:
'g' in s
[27]:
True
The range()
Function¶
[28]:
i = 1
while i <=10:
print(i)
i += 1
1
2
3
4
5
6
7
8
9
10
[29]:
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for element in l:
print(element)
1
2
3
4
5
6
7
8
9
10
[30]:
for element in range(1, 11):
print(element)
1
2
3
4
5
6
7
8
9
10
[31]:
for element in range(0, 10, 2):
print(element)
0
2
4
6
8
[32]:
for element in range(10):
print(element)
0
1
2
3
4
5
6
7
8
9
[33]:
r = range(3)
[34]:
for element in r:
print(element)
0
1
2
[35]:
type(r)
[35]:
range
[36]:
it = iter(r)
[37]:
type(it)
[37]:
range_iterator
[38]:
next(it)
[38]:
0
[39]:
next(it)
[39]:
1
[40]:
next(it)
[40]:
2
[41]:
try:
next(it)
except StopIteration:
pass
[42]:
for element in range(3):
print(element)
0
1
2
List Comprehension, Generator Expression¶
[123]:
def squares(iterable):
sq = []
for elem in iterable:
sq.append(elem**2)
return sq
for elem in squares([0,1,2,3,4]):
print(elem)
0
1
4
9
16
[127]:
for elem in [i**2 for i in [0,1,2,3,4]]:
print(elem)
0
1
4
9
16
[128]:
for elem in [i**2 for i in range(5)]:
print(elem)
0
1
4
9
16
Generator expression:
[130]:
for elem in (i**2 for i in range(5)):
print(elem)
0
1
4
9
16
[ ]:
[131]:
for elem in (i**2 for i in range(10) if i%2==0):
print(elem)
0
4
16
36
64
Strings¶
Literals¶
[43]:
'Hello'
[43]:
'Hello'
[44]:
"Hello"
[44]:
'Hello'
Quoting?¶
[45]:
'Hello \'World\''
[45]:
"Hello 'World'"
[46]:
"Hello 'World'"
[46]:
"Hello 'World'"
Embedded Newline Character
[47]:
docu = 'Das ist eine \nmehrzeilige Dokumentation\nvon irgendwas'
print(docu)
Das ist eine
mehrzeilige Dokumentation
von irgendwas
Multiline Strings¶
[48]:
docu = '''Das ist eine
mehrzeilige Dokumentation
von irgendwas'''
print(docu)
Das ist eine
mehrzeilige Dokumentation
von irgendwas
Raw Strings¶
Man hat Files mit folgendem deppertem Inhalt:
[49]:
line = 'irgendein irrelevanter quargel, Joerg, Faschingbauer, 190666'
Lösung: regular expressions
[50]:
import re
pattern = re.compile(r'^.*, (\w+), (\w+), (\d+)')
[51]:
match = pattern.search(line)
[52]:
if match is None:
print('Inkorrekte Zeile')
else:
print('Vorname:', match.group(1), 'Nachname:', match.group(2), 'Geburtsdatum:', match.group(3))
Vorname: Joerg Nachname: Faschingbauer Geburtsdatum: 190666
Functionality¶
[53]:
s = 'Hello World'
[54]:
s.capitalize()
[54]:
'Hello world'
[55]:
s = s.capitalize()
[56]:
s
[56]:
'Hello world'
[57]:
s.center(50)
[57]:
' Hello world '
[58]:
'mississippi'.count('ss')
[58]:
2
[59]:
'ein-excel-export.csv'.endswith('.csv')
[59]:
True
[60]:
'mississippi'.find('ss')
[60]:
2
[61]:
'mississippi'.find('sss')
[61]:
-1
[62]:
'mississippi'.index('ss')
[62]:
2
[63]:
try:
'mississippi'.index('sss')
except ValueError:
print('not found')
not found
[64]:
'abc'.isalpha()
[64]:
True
[65]:
'abc'.isidentifier()
[65]:
True
[66]:
'123'.isidentifier()
[66]:
False
[67]:
'123'.isidentifier()
[67]:
False
[68]:
'abc'.islower()
[68]:
True
[69]:
'ABC'.islower()
[69]:
False
[70]:
'-'.join(['Hello', 'World'])
[70]:
'Hello-World'
[71]:
'arg1,arg2,arg3'.split(',')
[71]:
['arg1', 'arg2', 'arg3']
strip()
and friends¶
[72]:
' blah blah \t\n '.strip()
[72]:
'blah blah'
[73]:
'abcblah blahabcbcabcc'.strip('abc')
[73]:
'lah blah'
[74]:
' abc '.rstrip()
[74]:
' abc'
[75]:
' abc '.lstrip()
[75]:
'abc '
String Formatting¶
[76]:
'Hello {0} {1}'.format('World', 666)
[76]:
'Hello World 666'
[77]:
'Hello {was} {wieviel}'.format(wieviel=666, was='World')
[77]:
'Hello World 666'
[78]:
'Hello {was:<10} {wieviel}'.format(wieviel=666, was='World')
[78]:
'Hello World 666'
f-Strings (since Python 3.6)¶
[79]:
wieviel = 666
was = 'Hello'
[80]:
f'Hello {was} {wieviel}'
[80]:
'Hello Hello 666'
[81]:
f'Hello {was:<10} {wieviel}'
[81]:
'Hello Hello 666'
datetime
¶
[82]:
import datetime
[83]:
now = datetime.datetime(2021, 7, 11, 23, 11, 33)
now
[83]:
datetime.datetime(2021, 7, 11, 23, 11, 33)
[84]:
delta = datetime.timedelta(days=3, seconds=39)
delta
[84]:
datetime.timedelta(days=3, seconds=39)
[85]:
now + delta
[85]:
datetime.datetime(2021, 7, 14, 23, 12, 12)
[86]:
now - delta
[86]:
datetime.datetime(2021, 7, 8, 23, 10, 54)
[87]:
now = datetime.datetime.now()
now
[87]:
datetime.datetime(2021, 8, 25, 15, 3, 10, 995237)
Parsing date formats¶
[88]:
datestr = '11.07.2021'
[89]:
dt = datetime.datetime.strptime(datestr, '%d.%m.%Y')
dt
[89]:
datetime.datetime(2021, 7, 11, 0, 0)
JSON¶
[90]:
import json
import uuid
Create a message object to, for example, transfer it via MQTT
[91]:
msg_aussi = {
'message': 'seas oida',
'msgid': uuid.uuid4().hex,
'timestamp': 345654325678,
}
Convert it to JSON for the transfer
[92]:
json_aussi = json.dumps(msg_aussi)
json_aussi
[92]:
'{"message": "seas oida", "msgid": "6563515ef0824d42b459389cefd09127", "timestamp": 345654325678}'
Transfer it
[93]:
json_eini = json_aussi
Convert JSON back to dictionary that the sender had, originally
[94]:
msg_eini = json.loads(json_eini)
msg_eini
[94]:
{'message': 'seas oida',
'msgid': '6563515ef0824d42b459389cefd09127',
'timestamp': 345654325678}