Python tips

Scroll Down
# fill zero of number
>>>a = '1'
>>>print(a)
1
>>>b = '1'.zfill(2*4)
>>>print(b)
00000001

# reverse sequence
>>>a = [0, 1, 2, 3, 4, 5]
>>>print(a[::-1])
[5, 4, 3, 2, 1, 0]

# str to variable
>>>eval('[1, 2, 3, 4]')
>>>[1, 2, 3, 4]

# reversed list or str
>>>reversed([1, 2, 3, 4])
>>>[4, 3, 2, 1]
>>>''.join(reversed('str1'))
>>>'1rts'

# filter max by key a from dictionary list
>>>list1 = [{'a': 10, 'b': 20}, {'a': 15, 'b': 22}, {'a': 1, 'b': 50}, {'a': 3, 'b': 36}]
>>>max(list1, key=lambda x: x['a'])
>>>{'a': 15, 'b': 22}

>>>You can use below function to check object if has attribute
hasattr(emp1, 'age')    # 如果存在 'age' 属性返回 True。
getattr(emp1, 'age')    # 返回 'age' 属性的值
setattr(emp1, 'age', 8) # 添加属性 'age' 值为 8
delattr(emp1, 'age')    # 删除属性 'age'
>>>import os
>>>hasattr(os, 'age')
>>>False
>>>hasattr(os, 'chmod')
>>>True