These can help you writer better (or at least more pythonic) code.
| Escape character | Description |
|---|---|
|
Backslash |
|
Single quote |
|
Double quote |
|
ASCII bell (BEL) |
|
ASCII backspace (BS) |
|
ASCII formfeed (FF) |
|
ASCII linefeed (LF) |
|
Character named name in the Unicode database (Unicode only) |
|
ASCII carriage return (CR) |
|
ASCII horizontal tab (TAB) |
|
Character with a 16-bit hex value xxxx (Unicode only) |
|
Character with a 32-bit hex value xxxxxxxx (Unicode only) |
|
ASCII vertical tab (VT) |
|
Character with octal value oo |
|
Character with hex value hh |
Python offers many different ways to format strings, all the methods below achieve the same output.
fname = 'Bob'
lname = 'Smith'
print('My name is %s %s.' % (fname, lname))
print('My name is %(fname)s %(lname)s.' % {'fname': fname, 'lname': lname})
print('My name is {} {}.'.format(fname, lname))
print('My name is {fname} {lname}.'.format(fname=fname, lname=lname))
print(f'My name is {fname} {lname}.')Used to generate lists and dictionaries with less code
numbers = [i for i in range(11)]
squares = [i**2 for i in numbers]Used to create inline functions, which is useful when no full-sized function is needed.
x = lambda a, b: a * b
print(x(4, 5))Test if a value is above a certain threshold:
check_value = lambda x: x > 1
check_value(0.7) #returns False
check_value(1.3) #returns TrueAssigns all three variables a, b and c to the value 5.
a = b = c = 5All items of a list can be assigned to variables, if there are the same amount of variables.
In this example all list elements get assigned to the provided variables, from left to right, respectively.
colors = ['red', 'blue', 'green', 'yellow']
firetruck, water, flower, sun, = colorsAfter executing this snippet, the variables have the following values.
firetruck = 'red'
water = 'blue'
leaf = 'green'
flower = 'yellow'Short if-else statements can be replaced with ternary conditions.
if a:
x = 1
else:
x = 2
= becomes
x = 1 if a else 2In Python, args and kwargs allow functions to take an unspecified amount of input values.
def print_args(*args):
for item in args:
print(item)
print_args(12, 'Hello World', 2.4)
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(key, value)
print_kwargs(id_1=10, id_2="Hello World")When working with large numbers it can be useful to highlight every third position.
num1 = 10000000
num2 = 10_000_000 # these are the same
print(f'{num2:,}') # 10,000,000To loop over multiple lists with one for loop, use the zip function. It stops as soon as the shortest list is exhausted.
To process all lists regardless of their length, use itertools.zip_longest().
for a, b in zip(list_a, list_b):
print(a, b)a, b = (1, 2) # need as many values as can be unpacked
a, b, *c = (1, 2, 3, 4) # a = 1, b = 2, c = [3, 4]
a, *_ = (1, 2, 3) # a = 1, throw the rest away
a, *b, c = (1, 2, 3, 4, 5) # a = 1, b = [2, 3, 4], c = 5When unpacking objects, the setattr and getattr functions can come in handy.
for key, value in dict.items():
setattr(object, key, value)When user input should not be displayed (e.g. for passwords), use the getpass.getpass() function.
Abstract classes have the characteristic that you cannot create objects with them. In addition, abstract methods need to be implemented by the child class.
Abstract classes inherit from ABC and abstract methods need the decorator @abstractmethod.
= ABC = Abstract Base Class
from abc import ABC, abstractmethod
class parent(ABC):
@abstractmethod
def test_method(self):
pass
class child(parent):
def test_method(self, text):
self.text = text
obj = child()
obj.test_method("HELLO")
print(test1.text)