Python Cheat Sheet 8 Pages
Python Cheat Sheet 8 Pages
io/
1. Basics: A. Datatypes & Conversion
SL Category / Datatype Variable declaration Class Type Conversion
1 Numeric – int, float, complex v1 = 1 # int | v2 = 1.0 # float type(v1) <class 'int'>| type(v2) <class 'float'> int() | float()
2 Text – String v3 = "apple" type(v3) is <class 'str'> str()
3 Sequence – List v4 = ['apple','banana','cucumber'] type(v4) is <class 'list'> list()
4 Sequence – Tuple v5 = ('apple','banana','cucumber') type(v5) is <class 'tuple'> tuple()
5 Set – Set, Frozenset v6a={'apple','banana'}|v6b=set((1,2,3)) type(v6a | vb6) is <class 'set'> set()
6 Mapping – Dictionary v7 = {'apple':1,'banana':2,} type(v7) is <class 'dict'> dict()
7 Boolean – bool v8 = True type( True ) is <class 'bool'> bool()
8 Others – (Binary, None) (Binary) bytes, bytearray, memoryview, (None type) None
24 Input() - default message ans = input('What is your name? '); print(ans) input() is prompting a default msg. first
before printing user provided input.
25 debugging using pdb import pdb | a = 19; b = 0 | pdb.set_trace() | addition = a+b | substraction = a-b | pdb.set_trace() | …
Common PDB commands,
# 1. l (list, shows all lines and show the debugging cursor (line number) where execution is paused)
# 2. n (next, executes current line, and moves to next line)
# 3. p (print, print variable values to check manually)
# 4. c (continue, executes all the remaining commands until end or a new pdb.set_trace() line found.)
26 Function as Decorator def decorator_func(func):
print("prerequisites"); return func # decorator function must return the original function
@decorator_func # Here, @decorator function name is passed
def orginal_function(): print("main")
orginal_function() >> prerequisites \n main # original function first executes decorator function
27 Class as Decorator class deco: # class decorator that prints the called function result
def __init__(self,func):
self.func = func
def __call__(self, *args, **kwargs): # wrapper function that executes the orginal function
print(f"class decorator code: {self.func.__name__,*args}") # Extra code on top of original function
print(f"Output: {self.func(*args, **kwargs)}") # executes the original function
@deco
def add(x,y): return x+y >> class decorator code before executing: ('add', 10, 20) \n Output: 30
28 Decorator with Arguments def p(func): # decorator function that prints the called function result
def wrapper(*args, **kwargs): # wrapper function that executes the orginal function
print(f"wrapper code to modify:{func.__name__, *args}") # Extra code on top of original function
print(f”Output: {func(*args, **kwargs)}”) # executes the original function
return wrapper # returns the original function after decoration/wrapper codes
@p
def add(x,y): return x+y >> wrapper code to modify:('add', 10, 20) \n Output: 30
29 regex search() search() & match() return match for partial string match but fullmatch() requires whole string match.
vs match() re.search("^x", 'x123sd432df')) returns <re.Match object; span=(0, 1), match='x'>
vs fullmatch() re.match("^x", 'x123sd432df')) returns <re.Match object; span=(0, 1), match='x'>
re.fullmatch("^x", 'x123sd432df') returns None
but, re.fullmatch("^x\w*",'x123sd432df') returns <re.Match object; span=(0, 11), match='x123sd432df'>
30 re split() subtext extraction txt='x123sd432df' ; exp="[0-9]+" ; print(re.split(exp,txt)) >> ['x', 'sd', 'df'] #extract text between numbers
31 re findall() numbers extraction txt='x123sd432df' ; exp="[0-9]+" ; print(re.findall(exp,txt)) >> ['123', '432'] #extract numbers in whole text
32 re sub() replace txt='x123sd432df' ; old="[0-9]+" ; new=”” print(re.sub(old, new, txt)) >> xsddf
& extract text or numbers txt='x123sd432df' ; old="[a-z]+" ; new=”” print(re.sub(old, new, txt)) >> 123432
33 Extraction of digits-letters txt=’ -_!||{}^:;/\<>*PO Number generated 13982020 successfully****()^!@#$%%_&’
alphanumerals & special chars 1. Numbers: re.sub("[^0-9]",'', txt) >> 13982020
from given text 2. Letters: re.sub("[^a-zA-Z]",'', txt) >> PONumbergeneratedsuccessfully
3. Spl chars: re.sub("[a-zA-Z0-9]",'', txt) >> `-_!||{}^:;/\<>* ****()^!@#$%%_&
4. AlphaNumerals: re.sub("[^a-zA-Z0-9]",'', txt) >> PONumbergenerated13982020successfully
34 re match groups() txt = 'username@hackerrank.com' ; exp= r'(\w+)@(\w+)\.(\w+)' ; m=re.match(exp,txt);
print(m.groups()) #>> ('username', 'hackerrank', 'com)
print(m.group(0)) #>> 'username@hackerrank.com' (The entire match)
print(m.group(1)) #>> 'username' (The first parenthesized subgroup)
print(m.group(2)) #>> 'hackerrank' (The second parenthesized subgroup)
print(m.group(3)) #>> 'com' >> (The third parenthesized subgroup)
print(re.findall(exp, txt)) #>> [('username', 'hackerrank', 'com')] (a list of group tuple)
35 re match groupdict() with re.match(r’(?P<user>\w+)@(?P<domain>\w+)\.(?P<ext>\w+)’,’jbasu@hackerrank.com’).groupdict()
named parameter >> {‘user’: ‘jbasu’, ‘domain’: ‘hackerrank’, ‘ext’: ‘com’}
36 re flags=re.DOTALL txt = """ Extract below code,
multi-line extraction ``` # delimiter ``` starts here, to be used in reg expression
x = 10; y = 20
print(x+y)
``` # delimiter ends here. re.DOTALL enforces Multi-line search including (\n).
That's all!
"""
print(re.findall("```(.*)```", txt, flags=re.DOTALL)) >> ['\nx = 10\ny = 20\nprint(x+y)\n']
37 re Number range validation print(bool(re.match(r'[1-9][0-9]{5}$', num))) >> validates ‘num’ between 100000 - 999999
38 re.findall - Positive lookahead Alternative repetitive numbers find: print(re.findall(r'(\d)(?=\d\1)', "13717919")) >> [‘7’, ‘9’]
Here, \d → Match and capture a digit in group | (?= →Start lookahead | \d → Match any digit
\1: Back-reference to captured group for searching for same digit | ) → End lookahead
7. Special Ops
# Special Operations Example Result/Note
1 HTML element attributes html_str = ‘ a src=”http www example.com” alt=”beautiful mountain” href=”http://example.com” ‘
extraction (key:value) print(re.findall(“\s(.*?)=[\”|\’](.*?)[\”|\’]”, html.strip())) returns,
[(‘src’, ‘http www example.com’), (‘alt’, ‘beautiful mountain’), (‘href’, ‘http://example.com’)]
2 eval() & exec() on string lst=[1,2,3]; eval("print([x**2 for x in "+str(lst)+"])") >> [1, 4, 9]
formatted exp (dynamic code) exec("print([x**2 for x in "+str(lst)+"])") >> [1, 4, 9]
3 Use of Zip() on multiple A = [1,2,3,'c']; B = [6,5,4,10,11,12,13,14,15]; C = [7]; print(list(zip(A,B,C))) >> [(1, 6, 7)]
iterables t1 = "Joydeep"; t2 = "Basu"; print(list(zip(t1,t2))) >> [('J', 'B'), ('o', 'a'), ('y', 's'), ('d', 'u')]
4 Use of exit() > Stop execution p = print; p("Hello, world!") Hello, world
exit() [note: print(Bye bye!”) is unreachable because
p("Bye bye!") code stops at exit()]
5 empty iterable as looping/if- a = [] while condition is False as a is empty so loop
else condition while a: print(‘Not empty’) >> prints nothing never executes.
6 Ternary conditional operation print('kid' if age < 18 else 'adult') <exp1> if <condition> else <exp2>
print('kid' if age < 13 else 'teen' if age < 18 else 'adult')
7 Overlapping substring string’s count() method returns Non-overlapping count If, String: Banana and Substring: ana
frequency of substring but it fails for overlapping substring cases. ostr.count(sstr) returns 1 (actual count 2).
To overcome this, This can be achieved using below:
Use a while loop until ostr.find(sstr) returns -1 with while ostr.find(sstr)>=0:
original string slicing[last_match_index+1:] cnt+=1; ostr=ostr[ostr.find(sstr)+1:]
8 Comprehension without storing even, odd, nums = [],[], [1,2,3,4,5,6,7,8,9,44,45,46,47,48,49,100,101,102,103,104,105]
results [odd.append(x) if x%2!=0 else even.append(x) for x in nums if x<100] → (this result list is not stored)
9 Print all built-ins print(dir(builtins)) import builtins (required to import first)
10 Print all local scope names def func1(): a=10; s1={1,2,3,5}; For this function, print(dir()) >> [‘a’,’s1’]
11 Print all global & local scope a,b,c=10,[0,1,2,3,4,5], {1:'Joy', 2:'Deep', 3:'Basu'}
runtime parameters print(globals()) # globals() returns the dictionary implementing the current module namespace.
print(locals()) # locals() returns a dictionary with the current local symbol table.
12 Debugging - use of a = {1:'Joy', 2:[]} ; txt = 'History' Here, breakpoint() pauses the execution
breakpoint() breakpoint() and enters into debugging mode. Remaining
a[2]=txt; print(a) code waits until quit debugging mode.
13 Text message encoding def encode(txt): return print(bytes(txt, encoding='utf-8')) Note: use bytearray for array of bytes.