Show Menu
Cheatography

Python Cheat Sheet (DRAFT) by

Personal python cheatsheet

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Loops

for i in range(x):
for v in list:
for idx, val in enumerate(iterable, start=0):
[expre­ssion for item in list]
while true expression:

Condit­ionals

if condition: ... elif condition: ... else: ...
[a for ... if condition]
[a if condition else b for ..]
10 > a > 100
if (x:=a+b) > c:
 

Strings

f'Variable {x} substi­tution'

Regular Expres­sions

import re
re.compile(pattern)
returns a regex object
re.search(pattern, string)
Find the first match and return a match object
re.match(pattern, string)
Returns a match object if the beginning of the string matches
re.split(pattern, string, maxsplit)
Split string by occurr­ences of pattern, complex!
re.findall(pattern, string)
Return all non-ov­erl­apping matches as a list of strings
re.fin­diter(pattern, string)
Returns in iterator yielding match objects over non-ov­erl­apping matches
re.sub(pattern, repl, string, count)
Returns a string, replacing the first occurrence of pattern with the repl string
re.sub(pattern, repl, string, count)
Similar to sub but return a tuple (new_s­tring, number­_of­_su­bs_­made)
 

Container Types

List
[] or [item1­,item2] or list([­ite­rable])
Ordered
Tuple
() or (item1, item2) or tuple(­[it­era­ble])
Ordered, Immutable
Dictionary
{} or {key: value} or dict(a=1, b=2)
No a priori order, unique keys
Collection / Set
set() or {1,2,3} or set{key1, key2}
No a priori order, unique keys
String
'' or 'item' or str('i­tem')
String is also iterable, immutable