Python Basics (2023-05-15 - 2023-05-17)¶
[1]:
code = '[1,2,3]'
[2]:
type(code)
[2]:
str
blah blah
[3]:
eval(code)
[3]:
[1, 2, 3]
Syntax etc.¶
[4]:
def add(a, b):
'Complex algorithm to add two numbers'
return a+b
[5]:
print(type(add))
<class 'function'>
[6]:
add.__doc__
[6]:
'Complex algorithm to add two numbers'
[7]:
help(add)
Help on function add in module __main__:
add(a, b)
Complex algorithm to add two numbers
[8]:
class Foo:
'pointless class'
[9]:
Foo.__doc__
[9]:
'pointless class'
[10]:
help(Foo)
Help on class Foo in module __main__:
class Foo(builtins.object)
| pointless class
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
Was ist das mit __
?
[11]:
class Bar:
def __init__(self, param):
self.member = param
[12]:
b = Bar(42)
[13]:
class Bar:
def __init__(self, param):
self.member = param
def doSomething(self):
return self.member**2
[14]:
b = Bar(42)
b.doSomething()
[14]:
1764
[15]:
print(b)
<__main__.Bar object at 0x7fe7fbf80df0>
[16]:
class Bar:
def __init__(self, param):
self.member = param
def doSomething(self):
return self.member**2
def __str__(self):
return f'Ein nettes sinnloses Objekt mit dem Wert {self.member}'
[17]:
b = Bar(42)
[18]:
print(b)
Ein nettes sinnloses Objekt mit dem Wert 42
Variables¶
[19]:
a = 42
[20]:
print(type(a))
<class 'int'>
[21]:
a = 1.5
[22]:
print(type(a))
<class 'float'>
[23]:
a = 'blah'
[24]:
print(type(a))
<class 'str'>
[25]:
a = [1,2,3]
print(type(a))
<class 'list'>
Tuple unpacking
[26]:
a = 1
b = 2
[27]:
a
[27]:
1
[28]:
b
[28]:
2
[29]:
a, b = 1, 2
[30]:
x = 1, 2
[31]:
print(type(x))
<class 'tuple'>
[32]:
x
[32]:
(1, 2)
[33]:
try:
a, b, c = 1, 2
except Exception as e:
print(e, type(e))
not enough values to unpack (expected 3, got 2) <class 'ValueError'>
[34]:
print('hier bin ich')
hier bin ich
[35]:
a, b
[35]:
(1, 2)
[36]:
tmp = a
a = b
b = tmp
[37]:
a, b
[37]:
(2, 1)
[38]:
a, b = b, a
[39]:
a, b
[39]:
(1, 2)
Object Identity
[40]:
a = 42
[41]:
id(a)
[41]:
140634424624656
[42]:
b = a
[43]:
id(b)
[43]:
140634424624656
[44]:
b = 7
[45]:
id(b)
[45]:
140634424623536
[46]:
id(a)
[46]:
140634424624656
Datatypes¶
[47]:
i = 42
[48]:
i = -42
[49]:
i
[49]:
-42
[50]:
i = 0o644
[51]:
i
[51]:
420
[52]:
i = 0xdeadbeef
[53]:
i
[53]:
3735928559
[54]:
i = 0b01110101
[55]:
i
[55]:
117
[56]:
i = 2**64-1
[57]:
bin(i)
[57]:
'0b1111111111111111111111111111111111111111111111111111111111111111'
[58]:
len(bin(i))
[58]:
66
[59]:
i += 1
[60]:
i
[60]:
18446744073709551616
[61]:
len(bin(i))
[61]:
67
[62]:
10**1000
[62]:
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
[63]:
3/2
[63]:
1.5
[64]:
3//2
[64]:
1
[65]:
l1 = [1,2,3]
l2 = [2,3,4]
try:
l1*l2
except Exception as e:
print(e, type(e))
can't multiply sequence by non-int of type 'list' <class 'TypeError'>
[66]:
l1 + l2
[66]:
[1, 2, 3, 2, 3, 4]
Datatype Conversions¶
[67]:
i = 42
[68]:
s = str(i)
[69]:
s
[69]:
'42'
[70]:
i.__str__()
[70]:
'42'
[71]:
i.__float__()
[71]:
42.0
[72]:
f = float(i)
[73]:
f
[73]:
42.0
[74]:
int(f)
[74]:
42
[75]:
f.__int__()
[75]:
42
[76]:
s = '42'
[77]:
int(s)
[77]:
42
[78]:
int(s, 16)
[78]:
66
[79]:
s = '0xdeadbeef'
[80]:
try:
int(s)
except Exception as e:
print(e, type(e))
invalid literal for int() with base 10: '0xdeadbeef' <class 'ValueError'>
[81]:
int(s, 16)
[81]:
3735928559
[82]:
1 + 2.3
[82]:
3.3
[83]:
try:
'1' + 2
except Exception as e:
print(e, type(e))
can only concatenate str (not "int") to str <class 'TypeError'>
[84]:
try:
'1'.__add__(2)
except Exception as e:
print(e, type(e))
can only concatenate str (not "int") to str <class 'TypeError'>
Difference between ctor and eval()
?
[85]:
int('42')
[85]:
42
[86]:
eval('42')
[86]:
42
[87]:
s = '[1,2,3]'
[88]:
list(s)
[88]:
['[', '1', ',', '2', ',', '3', ']']
[89]:
eval(s)
[89]:
[1, 2, 3]
[90]:
code = '''
i = 0
while i<42:
i+=1
print(i)
'''
[91]:
type(code)
[91]:
str
[92]:
exec(code)
42
[93]:
config = '''
SETTING_BLAH = 42
SETTING_FOO = 'jo oida'
'''
[94]:
config_context = {}
[95]:
exec(config, config_context)
[96]:
config_context['SETTING_BLAH']
[96]:
42
Immutable vs. Mutable¶
[97]:
def foo(a):
print(id(a))
[98]:
x = 666
[99]:
id(x)
[99]:
140634341074320
[100]:
foo(x)
140634341074320
[101]:
x = 42
[102]:
id(x)
[102]:
140634424624656
[103]:
x += 1
[104]:
id(x)
[104]:
140634424624688
[105]:
x = 42
[106]:
id(x)
[106]:
140634424624656
[107]:
x = 1234
[108]:
y = 1234
[109]:
x is y
[109]:
False
[110]:
id(x)
[110]:
140634341076688
[111]:
id(y)
[111]:
140634341077776
Memory Management
[112]:
abc = 666
[113]:
del abc
[114]:
try:
abc
except Exception as e:
print(e, type(e))
name 'abc' is not defined <class 'NameError'>
[115]:
f = open('/etc/passwd')
[116]:
f.close()
[117]:
with open('/etc/passwd') as f:
print(len(list(f)))
48
Compound Datatypes¶
List, Tuple¶
[118]:
l = [1,2,'drei']
[119]:
len(l)
[119]:
3
[120]:
l.append(4)
[121]:
len(l)
[121]:
4
[122]:
l
[122]:
[1, 2, 'drei', 4]
[123]:
l1 = [5, 'sechs']
[124]:
l.extend(l1)
[125]:
l
[125]:
[1, 2, 'drei', 4, 5, 'sechs']
[126]:
l.append(l1)
[127]:
l
[127]:
[1, 2, 'drei', 4, 5, 'sechs', [5, 'sechs']]
[128]:
l.reverse()
[129]:
l
[129]:
[[5, 'sechs'], 'sechs', 5, 4, 'drei', 2, 1]
[130]:
l += l1
[131]:
l
[131]:
[[5, 'sechs'], 'sechs', 5, 4, 'drei', 2, 1, 5, 'sechs']
[132]:
t = (1,2,'drei')
[133]:
try:
t.append(4.0)
except Exception as e:
print(e, type(e))
'tuple' object has no attribute 'append' <class 'AttributeError'>
[134]:
t1 = (5, 'sechs')
[135]:
id(t)
[135]:
140634343012864
[136]:
t += t1
[137]:
id(t)
[137]:
140634341099856
The `in`` operator
[138]:
l = [3,4,1,'fuenf']
[139]:
3 in l
[139]:
True
[140]:
5 not in l
[140]:
True
[141]:
not 5 in l
[141]:
True
[142]:
'fuenf' in l
[142]:
True
[143]:
6 in l
[143]:
False
Dictionary¶
[144]:
d = {'one': 1, 'two': 2, 3: 'three'}
[145]:
d['one']
[145]:
1
[146]:
try:
d['three']
except Exception as e:
print(e, type(e))
'three' <class 'KeyError'>
[147]:
'three' in d
[147]:
False
[148]:
value = d.get('three')
[149]:
print(value)
None
[150]:
d['three'] = 3
[151]:
'three' in d
[151]:
True
[152]:
del d['three']
[153]:
'three' in d
[153]:
False
[154]:
d
[154]:
{'one': 1, 'two': 2, 3: 'three'}
Set¶
[155]:
s = {1,2,'drei'}
[156]:
s.add(4.0)
[157]:
s.remove('drei')
[158]:
2 in s
[158]:
True
[159]:
l = [1,2,3]
[160]:
s.add(l)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_61373/1125713270.py in <module>
----> 1 s.add(l)
TypeError: unhashable type: 'list'
[ ]:
i = 42
i.__hash__()
[ ]:
i = 1234567876543234567654321234565432123456
i.__hash__()
[ ]:
s.add((1,2,3))
Slicing¶
[ ]:
l = [2,3,4,5,6]
[ ]:
l[2:4]
[ ]:
l[2:5]
[ ]:
l[2:len(l)]
[ ]:
l[2:len(l)-1]
[ ]:
l[2:-1]
[ ]:
l[1]
[ ]:
l[1]
[ ]:
l[0]
[ ]:
try:
l[len(l)]
except Exception as e:
print(e, type(e))
[ ]:
l[len(l)-1]
[ ]:
l[-1]
[ ]:
l[0:6]
[ ]:
l[0:]
[ ]:
l[:]
[ ]:
l[1:]
for
¶
[161]:
for name in ['Caro', 'Johanna', 'Eva', 'Jörg']:
print(name)
Caro
Johanna
Eva
Jörg
[162]:
l = [0,1,2,3,4]
for elem in l:
print(elem)
0
1
2
3
4
[163]:
for elem in range(5):
print(elem)
0
1
2
3
4
[164]:
r = range(5)
[165]:
print(type(r))
<class 'range'>
Iterator Protocol¶
[166]:
r = range(3)
[167]:
it = iter(r)
[168]:
next(it)
[168]:
0
[169]:
next(it)
[169]:
1
[170]:
next(it)
[170]:
2
[171]:
try:
next(it)
except Exception as e:
print(e, type(e))
<class 'StopIteration'>
[172]:
l = [0,1,2]
[173]:
it = iter(l)
[174]:
next(it)
[174]:
0
[175]:
next(it)
[175]:
1
[176]:
next(it)
[176]:
2
[177]:
try:
next(it)
except Exception as e:
print(e, type(e))
<class 'StopIteration'>
[178]:
def my_range(n):
current = 0
yield current
while current < n:
yield current
current += 1
[179]:
r = my_range(3)
[180]:
print(type(r))
<class 'generator'>
[181]:
it = iter(r)
[182]:
next(it)
[182]:
0
[183]:
next(it)
[183]:
0
[184]:
next(it)
[184]:
1
[185]:
next(it)
[185]:
2
[186]:
try:
next(it)
except Exception as e:
print(e, type(e))
<class 'StopIteration'>
The range
Function¶
[187]:
for elem in range(3):
print(elem)
0
1
2
[188]:
for elem in range(0,3):
print(elem)
0
1
2
[189]:
for elem in range(1,4):
print(elem)
1
2
3
[190]:
for elem in range(1,7,2):
print(elem)
1
3
5
[191]:
list('abc')
[191]:
['a', 'b', 'c']
[192]:
for elem in 'abc':
print(elem)
a
b
c
[193]:
for elem in range(3):
print(elem)
0
1
2
[194]:
list(range(3))
[194]:
[0, 1, 2]
[195]:
for elem in ['Joerg', 'Johanna', 'Caro', 'Philipp', 'Eva']:
print(elem)
Joerg
Johanna
Caro
Philipp
Eva
[196]:
i = 0
for elem in ['Joerg', 'Johanna', 'Caro', 'Philipp', 'Eva']:
print(i, elem)
i += 1
0 Joerg
1 Johanna
2 Caro
3 Philipp
4 Eva
[197]:
for elem in enumerate(['Joerg', 'Johanna', 'Caro', 'Philipp', 'Eva']):
print(elem)
(0, 'Joerg')
(1, 'Johanna')
(2, 'Caro')
(3, 'Philipp')
(4, 'Eva')
[198]:
for elem in enumerate(['Joerg', 'Johanna', 'Caro', 'Philipp', 'Eva']):
pos = elem[0]
name = elem[1]
print(pos, name)
0 Joerg
1 Johanna
2 Caro
3 Philipp
4 Eva
[199]:
for pos, name in enumerate(['Joerg', 'Johanna', 'Caro', 'Philipp', 'Eva']):
print(pos, name)
0 Joerg
1 Johanna
2 Caro
3 Philipp
4 Eva
[200]:
for pos, elem in enumerate(range(3, 7)):
print(pos, elem)
0 3
1 4
2 5
3 6
References, (Im)mutability¶
[201]:
a = 42
[202]:
b = a
[203]:
id(a), id(b)
[203]:
(140634424624656, 140634424624656)
[204]:
a = 666
[205]:
b
[205]:
42
[206]:
id(a)
[206]:
140634281233520
[207]:
id(b)
[207]:
140634424624656
[208]:
l1 = [1,2,3]
[209]:
l2 = l1
[210]:
l2.append(4)
[211]:
l2
[211]:
[1, 2, 3, 4]
[212]:
l1
[212]:
[1, 2, 3, 4]
[213]:
l1 = [1,2,3]
l2 = l1[:]
[214]:
id(l1), id(l2)
[214]:
(140634341798400, 140634341995008)
[215]:
l1 = [1, ['a', 'b'], 2]
[216]:
id(l1)
[216]:
140634341576640
[217]:
l2 = l1[:]
[218]:
id(l2)
[218]:
140634341773312
[219]:
l1.append(3)
[220]:
l1
[220]:
[1, ['a', 'b'], 2, 3]
[221]:
l2
[221]:
[1, ['a', 'b'], 2]
[222]:
l1[1]
[222]:
['a', 'b']
[223]:
l2[1]
[223]:
['a', 'b']
[224]:
l1[1].append('c')
[225]:
l1
[225]:
[1, ['a', 'b', 'c'], 2, 3]
[226]:
l2
[226]:
[1, ['a', 'b', 'c'], 2]
[227]:
id(l1[1])
[227]:
140634281802304
[228]:
id(l2[1])
[228]:
140634281802304
Functions¶
[229]:
def foo(a):
return a**2
[230]:
print(type(foo))
<class 'function'>
[231]:
x = foo
[232]:
x(2)
[232]:
4
[233]:
foo = 666
[234]:
try:
foo(2)
except Exception as e:
print(e, type(e))
'int' object is not callable <class 'TypeError'>
[235]:
global_variable = 666
[236]:
def bar():
print(global_variable)
[237]:
bar()
666
[238]:
def bar2():
global_variable = 42
[239]:
bar2()
[240]:
global_variable
[240]:
666
[241]:
def bar3():
global global_variable
global_variable = 42
[242]:
bar3()
[243]:
global_variable
[243]:
42
[244]:
def bar4(param=42):
print(param)
[245]:
bar4(666)
666
[246]:
bar4()
42
[247]:
def bar5(param=[]):
print(param)
[248]:
bar5(42)
42
[249]:
bar5()
[]
[250]:
def bar6(param=[]):
param.append(666)
print(param)
[251]:
bar6()
[666]
[252]:
bar6()
[666, 666]
[253]:
dir(bar6)
[253]:
['__annotations__',
'__builtins__',
'__call__',
'__class__',
'__closure__',
'__code__',
'__defaults__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__get__',
'__getattribute__',
'__globals__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__kwdefaults__',
'__le__',
'__lt__',
'__module__',
'__name__',
'__ne__',
'__new__',
'__qualname__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__']
[254]:
bar6.__defaults__
[254]:
([666, 666],)
[255]:
bar6()
[666, 666, 666]
[256]:
bar6()
[666, 666, 666, 666]
[257]:
bar6([42])
[42, 666]
[258]:
bar6()
[666, 666, 666, 666, 666]
[259]:
l = [42]
bar6(l)
[42, 666]
[260]:
l
[260]:
[42, 666]
And ``yield``?
[261]:
def f():
return 42
return 666
[262]:
f()
[262]:
42
[263]:
type(f)
[263]:
function
[264]:
def f():
yield 42
yield 666
[265]:
type(f)
[265]:
function
[266]:
f()
[266]:
<generator object f at 0x7fe7f869b7d0>
[267]:
gen = f()
[268]:
gen
[268]:
<generator object f at 0x7fe7f869b920>
[269]:
for i in gen:
print(i)
42
666
[270]:
def f():
print('start, yielding 42')
yield 42
print('after yield 42, yielding 666')
yield 666
print('after yield 666')
[271]:
gen = f()
gen
[271]:
<generator object f at 0x7fe7f869bbc0>
[272]:
for i in gen:
print(i)
start, yielding 42
42
after yield 42, yielding 666
666
after yield 666
[273]:
gen = f()
[274]:
it = iter(gen)
[275]:
next(it)
start, yielding 42
[275]:
42
[276]:
next(it)
after yield 42, yielding 666
[276]:
666
[277]:
try:
next(it)
except Exception as e:
print(e, type(e))
after yield 666
<class 'StopIteration'>
Miscellaneous String Methods¶
[278]:
s = 'abc'
[279]:
print(type(s))
<class 'str'>
[280]:
help(str)
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __format__(self, format_spec, /)
| Return a formatted version of the string as described by format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \\n \\r \\t \\f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits (starting from the left).
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \\n \\r \\t \\f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits (starting from the left).
| -1 (the default value) means no limit.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
[281]:
s*5
[281]:
'abcabcabcabcabc'
[282]:
s.__sizeof__()
[282]:
52
[283]:
'abcd'.__sizeof__()
[283]:
53
[288]:
s.__len__()
[288]:
3
[289]:
len(s)
[289]:
3
[290]:
s.__gt__('aaa')
[290]:
True
[292]:
s > 'aaa'
[292]:
True
[285]:
s.capitalize()
[285]:
'Abc'
[286]:
s
[286]:
'abc'
[293]:
s = 'mississippi'
[294]:
s.count('ss')
[294]:
2
[295]:
s.count('i')
[295]:
4
[296]:
s.upper()
[296]:
'MISSISSIPPI'
[297]:
s.upper().lower()
[297]:
'mississippi'
[298]:
filename = 'blah.csv'
[299]:
filename.endswith('.csv')
[299]:
True
[300]:
filename.startswith('xx')
[300]:
False
[301]:
s
[301]:
'mississippi'
[302]:
s.find('ss')
[302]:
2
[303]:
s.find('ss', 3)
[303]:
5
[305]:
s.find('ss', s.find('ss')+1)
[305]:
5
[306]:
s.find('xx')
[306]:
-1
[307]:
s.index('ss')
[307]:
2
[309]:
try:
s.index('xx')
except ValueError as e:
print(e, type(e))
substring not found <class 'ValueError'>
[310]:
line = '5;Joerg;Faschingbauer'
[311]:
line.split(';')
[311]:
['5', 'Joerg', 'Faschingbauer']
[313]:
line.split(';', 1)
[313]:
['5', 'Joerg;Faschingbauer']
[314]:
fields = ['5', 'Joerg', 'Faschingbauer']
[315]:
';'.join(fields)
[315]:
'5;Joerg;Faschingbauer'
[316]:
'abc'.center(50)
[316]:
' abc '
[317]:
line = ' \n abc \t '
[318]:
line.strip()
[318]:
'abc'
[319]:
line.strip(' ')
[319]:
'\n abc \t'
[320]:
line.rstrip()
[320]:
' \n abc'
[321]:
line.lstrip()
[321]:
'abc \t '
[323]:
import re
[324]:
line = 'ss ss ss 1234'
[330]:
rex = re.compile(r'^ss\s+ss\s+ss\s+(\d+)\s*$')
[331]:
match = rex.search(line)
[332]:
print(match)
<re.Match object; span=(0, 13), match='ss ss ss 1234'>
[333]:
match.group(1)
[333]:
'1234'
Lists¶
[335]:
l = [3,2,4,5,1,]
l.sort()
[336]:
l
[336]:
[1, 2, 3, 4, 5]
[337]:
l = [3,2,4,5,1,]
sorted(l)
[337]:
[1, 2, 3, 4, 5]
[338]:
l
[338]:
[3, 2, 4, 5, 1]
[339]:
sorted('cba')
[339]:
['a', 'b', 'c']
Dictionaries¶
[340]:
d = {'one': 1, 'two': 2}
d
[340]:
{'one': 1, 'two': 2}
[341]:
d = {}
[343]:
l = [('one', 1), ('two', 2)]
d = dict(l)
d
[343]:
{'one': 1, 'two': 2}
[344]:
d['one']
[344]:
1
[346]:
try:
d['three']
except Exception as e:
print(e, type(e))
'three' <class 'KeyError'>
[347]:
d.get('two')
[347]:
2
[349]:
value = d.get('three')
print(value)
None
[350]:
value = d.get('three')
if value is None:
print(3)
else:
print(value)
3
[351]:
d.get('three', 3)
[351]:
3
[352]:
d
[352]:
{'one': 1, 'two': 2}
[353]:
if 'three' in d:
value = d['three']
else:
d['three'] = 3
value = d['three']
print(value)
3
[354]:
d.setdefault('three', 3)
[354]:
3
[355]:
d
[355]:
{'one': 1, 'two': 2, 'three': 3}
[356]:
another_d = {'three': 3.0, 'four': 4.0, 'five': 5}
[357]:
d.update(another_d)
d
[357]:
{'one': 1, 'two': 2, 'three': 3.0, 'four': 4.0, 'five': 5}
[358]:
x = 666
x
[358]:
666
[359]:
del x
[361]:
try:
x
except Exception as e:
print(e, type(e))
name 'x' is not defined <class 'NameError'>
[362]:
d
[362]:
{'one': 1, 'two': 2, 'three': 3.0, 'four': 4.0, 'five': 5}
[363]:
del d['three']
[364]:
d
[364]:
{'one': 1, 'two': 2, 'four': 4.0, 'five': 5}
[366]:
for elem in d:
print(elem)
one
two
four
five
[367]:
for elem in d.keys():
print(elem)
one
two
four
five
[368]:
for elem in d.values():
print(elem)
1
2
4.0
5
[369]:
for elem in d.items():
print(elem)
('one', 1)
('two', 2)
('four', 4.0)
('five', 5)
[370]:
for elem in d.items():
key = elem[0]
value = elem[1]
print(f'key {key}, value {value}')
key one, value 1
key two, value 2
key four, value 4.0
key five, value 5
[376]:
for key, value in d.items():
print(f'key {key}, value {value}')
key one, value 1
key two, value 2
key four, value 4.0
key five, value 5
Good ol’ format():
[374]:
'key {key}, value {value}'.format(key=3, value='three')
[374]:
'key 3, value three'
[375]:
'key {0}, value {1}'.format(3, 'three')
[375]:
'key 3, value three'
File I/O¶
[377]:
f = open('/etc/passwd')
[379]:
f
[379]:
<_io.TextIOWrapper name='/etc/passwd' mode='r' encoding='UTF-8'>
[380]:
f.close()
[381]:
with open('/etc/passwd') as f:
pass
[382]:
f = open('/etc/passwd', encoding='ascii')
[384]:
try:
f.read()
except Exception as e:
print(e, type(e))
[385]:
f = open('/etc/passwd', encoding='utf-8')
[386]:
f.read()
[386]:
'root:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:/sbin/nologin\ndaemon: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'
[388]:
f = open('/etc/passwd', 'rb')
[390]:
f.read()
[390]:
b'root:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:/sbin/nologin\ndaemon: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\xc3\xb6rg 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'
[393]:
f.close()
[394]:
f = open('/etc/passwd', encoding='utf-8')
[395]:
f.read(10)
[395]:
'root:x:0:0'
[397]:
f.read(10)
[397]:
':root:/roo'
[398]:
_ = f.read(2640)
[399]:
len(_)
[399]:
2640
[400]:
s = f.read(30000)
[401]:
len(s)
[401]:
30
[403]:
s = f.read(3000)
[404]:
len(s)
[404]:
0
[405]:
f.seek(0)
[405]:
0
[406]:
f.read(10)
[406]:
'root:x:0:0'
[407]:
f = open('/etc/passwd', encoding = 'utf-8')
[408]:
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
CSV¶
[409]:
d = {
'ID': '5',
'Firstname': 'Joerg',
'Lastname': 'Faschingbauer',
}
[410]:
id, firstname, lastname = d
[411]:
id, firstname, lastname
[411]:
('ID', 'Firstname', 'Lastname')
[412]:
for elem in d:
print(elem)
ID
Firstname
Lastname
Lambda, And Functional Programming Tools¶
[413]:
def square(n): return n**2
[414]:
l = [0,1,2,3,4,5]
[415]:
for elem in l:
print(square(elem))
0
1
4
9
16
25
[417]:
for sq in map(square, l):
print(sq)
0
1
4
9
16
25
[419]:
for sq in map(lambda n: n**2, l):
print(sq)
0
1
4
9
16
25
[420]:
for sq in map(lambda n: n**2, range(6)):
print(sq)
0
1
4
9
16
25
[421]:
for even in filter(lambda n: n%2==0, range(6)):
print(even)
0
2
4
[423]:
for sq in (n**2 for n in range(6)):
print(sq)
0
1
4
9
16
25
[424]:
for even in (n for n in range(6) if n%2 == 0):
print(even)
0
2
4