This a summary of all the things we use in python. This can be a great help or reference for students who just started or a reference for seasoned coders.
Python has two main types of Numbers -
int ( or integers) and
float (or floating point numbers)
#integerstype(1) # inttype(-10) # inttype(0) # int#floating point numbers (decimal)type(0.0) # floattype(2.2) # floattype(4E2) # float - 4*10 to the power of 2# Arithmetic10+3# 1310-3# 710*3# 3010**3# 100010/3# 3.333333333333333510//3# 3 --> floor division - no decimals and returns an int10%3# 1 --> modulo operator - return the reminder. Good for deciding if number is even or odd# Basic Math Functions on int and floatpow(5, 2) # 25 --> like doing 5**2abs(-50) # 50round(5.46) # 5round(5.468, 2)# 5.47 --> round to nth digitbin(512) # '0b1000000000' --> binary formathex(512) # '0x200' --> hexadecimal format# Converting Strings to Numbersage=input("How old are you?")
age=int(age)
pi=input("What is the value of pi?")
pi=float(pi)Strings in python are stored as sequences of letters in memory. You can imgine it as a
type('Hellloooooo') # str#when needed a single quote in a string'I\'m thirsty'"I'm thirsty"#escape characters"\n"# new line"\t"# adds a tab# String slicing# index always starts with 0# : is called slicing and has the format [ start : end : step ]'Hey you!'[4] # yname='Tomorrow Never Dies'name[4] # rname[:] # Tomorrow Never Diesname[1:] # omorrow Never Diesname[:1] # Tname[-1] # sname[::1] # Tomorrow Never Diesname[::-1] # seiD reveN worromoTname[0:10:2]# Tmro N'Hi there '+'S44WN'# 'Hi there S44WN' --> This is called string concatenation#string multiplies'*'*10# **********'hey'*3#heyheyhey# Basic Functionslen('turtle') # 6# Basic Methods --' I am alone '.strip()
# 'I am alone' --> Strips all whitespace characters from both ends.'On an island'.strip('d')
# 'On an islan' --> # Strips all passed characters from both ends.'but life is good!'.split()
# ['but', 'life', 'is', 'good!']'Help me'.replace('me', 'you')
# 'Help you' --> Replaces first with second param'Need to make fire'.startswith('Need')# True'and cook rice'.endswith('rice') # True'still there?'.upper() # STILL THERE?'HELLO?!'.lower() # hello?!'ok, I am done.'.capitalize() # 'Ok, I am done.''oh hi there'.count('e') # 2'bye bye'.index('e') # 2'oh hi there'.find('i') # 4 --> returns the starting index position of the first occurrence'oh hi there'.find('a') # -1'oh hi there'.index('a') # Raises ValueError# String Formattingname1='Steve'name2='Peggy'print(f'Hello there {name1} and {name2}') # Hello there Steve and Peggy - Newer way to do things as of python 3.6print('Hello there {} and {}'.format(name1, name2))# Hello there Steve and Peggyprint('Hello there %s and %s'%(name1, name2)) # Hello there Steve and Peggy --> you can also use %d, %f, %r for integers, floats, string representations of objects respectively# Palindrome checkword='reviver'p=bool(word.find(word[::-1]) +1)
print(p) # TrueTrue or False. Used in a lot of comparison and logical operations in Python
bool(True)
bool(False)
# all of the below evaluate to False. Everything else will evaluate to True in Python.print(bool(None))
print(bool(False))
print(bool(0))
print(bool(0.0))
print(bool([]))
print(bool({}))
print(bool(()))
print(bool(''))
print(bool(range(0)))
print(bool(set()))
# See Logical Operators and Comparison Operators section for more on booleans.Unlike strings, lists are mutable sequences in python
my_list= [1, 2, '3', True]# We assume this list won't mutate for each example belowlen(my_list) # 4my_list.index('3') # 2my_list.count(2) # 1 --> count how many times 2 appearsmy_list[3] # Truemy_list[1:] # [2, '3', True]my_list[:1] # [1]my_list[-1] # Truemy_list[::1] # [1, 2, '3', True]my_list[::-1] # [True, '3', 2, 1]my_list[0:3:2] # [1, '3']# : is called slicing and has the format [ start : end : step ]# Add to Listmy_list*2# [1, 2, '3', True, 1, 2, '3', True]my_list+ [100] # [1, 2, '3', True, 100] --> doesn't mutate original list, creates new onemy_list.append(100) # None --> Mutates original list to [1, 2, '3', True, 100] # Or: <list> += [<el>]my_list.extend([100, 200]) # None --> Mutates original list to [1, 2, '3', True, 100, 200]my_list.insert(2, '!!!') # None --> [1, 2, '!!!', '3', True] - Inserts item at index and moves the rest to the right.' '.join(['Hello','There'])# 'Hello There' --> Joins elements using string as separator.# Copy a Listbasket= ['apples', 'pears', 'oranges']
new_basket=basket.copy()
new_basket2=basket[:]# Remove from List
[1,2,3].pop() # 3 --> mutates original list, default index in the pop method is -1 (the last item)
[1,2,3].pop(1) # 2 --> mutates original list
[1,2,3].remove(2)# None --> [1,3] Removes first occurrence of item or raises ValueError.
[1,2,3].clear() # None --> mutates original list and removes all items: []del [1,2,3][0] # None --> removes item on index 0 or raises IndexError# Ordering
[1,2,5,3].sort() # None --> Mutates list to [1, 2, 3, 5]
[1,2,5,3].sort(reverse=True) # None --> Mutates list to [5, 3, 2, 1]
[1,2,5,3].reverse() # None --> Mutates list to [3, 5, 2, 1]sorted([1,2,5,3]) # [1, 2, 3, 5] --> new list createdmy_list= [(4,1),(2,4),(2,5),(1,6),(8,9)]
sorted(my_list,key=lambdax: int(x[0])) # [(1, 6), (2, 4), (2, 5), (4, 1), (8, 9)] --> sort the list by 1st (0th index) value of the tuplelist(reversed([1,2,5,3]))# [3, 5, 2, 1] --> reversed() returns an iterator# Useful operations1in [1,2,5,3] # Truemin([1,2,3,4,5])# 1max([1,2,3,4,5])# 5sum([1,2,3,4,5])# 15# Get First and Last element of a listmList= [63, 21, 30, 14, 35, 26, 77, 18, 49, 10]
first, *x, last=mListprint(first) #63print(last) #10# Matrixmatrix= [[1,2,3], [4,5,6], [7,8,9]]
matrix[2][0] # 7 --> Grab first first of the third item in the matrix object# Looping through a matrix by rows:mx= [[1,2,3],[4,5,6]]
forrowinrange(len(mx)):
forcolinrange(len(mx[0])):
print(mx[row][col]) # 1 2 3 4 5 6# Transform into a list:
[mx[row][col] forrowinrange(len(mx)) forcolinrange(len(mx[0]))] # [1,2,3,4,5,6]# Combine columns with zip and *:
[xforxinzip(*mx)] # [(1, 3), (2, 4)]# List Comprehensions# new_list[<action> for <item> in <iterator> if <some condition>]a= [iforiin'hello'] # ['h', 'e', 'l', 'l', '0']b= [i*2foriin [1,2,3]] # [2, 4, 6]c= [iforiinrange(0,10) ifi%2==0]# [0, 2, 4, 6, 8]# Advanced Functionslist_of_chars=list('Helloooo') # ['H', 'e', 'l', 'l', 'o', 'o', 'o', 'o']sum_of_elements=sum([1,2,3,4,5]) # 15element_sum= [sum(pair) forpairinzip([1,2,3],[4,5,6])] # [5, 7, 9]sorted_by_second=sorted(['hi','you','man'], key=lambdael: el[1])# ['man', 'hi', 'you']sorted_by_key=sorted([
{'name': 'Bina', 'age': 30},
{'name':'Andy', 'age': 18},
{'name': 'Zoey', 'age': 55}],
key=lambdael: (el['name']))
# [{'name': 'Andy', 'age': 18}, {'name': 'Bina', 'age': 30}, {'name': 'Zoey', 'age': 55}]# Read line of a file into a listwithopen("myfile.txt") asf:
lines= [line.strip() forlineinf]Also known as mappings or hash tables. They are key value pairs that are guaranteed to retain order of insertion starting from Python 3.7
my_dict= {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False}
my_dict['name'] # Andrei Neagoielen(my_dict) # 3list(my_dict.keys()) # ['name', 'age', 'magic_power']list(my_dict.values()) # ['Andrei Neagoie', 30, False]list(my_dict.items()) # [('name', 'Andrei Neagoie'), ('age', 30), ('magic_power', False)]my_dict['favourite_snack'] ='Grapes'# {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes'}my_dict.get('age') # 30 --> Returns None if key does not exist.my_dict.get('ages', 0 ) # 0 --> Returns default (2nd param) if key is not found#Remove keydelmy_dict['name']
my_dict.pop('name', None)my_dict.update({'cool': True}) # {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes', 'cool': True}
{**my_dict, **{'cool': True} } # {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack': 'Grapes', 'cool': True}new_dict=dict([['name','Andrei'],['age',32],['magic_power',False]]) # Creates a dict from collection of key-value pairs.new_dict=dict(zip(['name','age','magic_power'],['Andrei',32, False]))# Creates a dict from two collections.new_dict=my_dict.pop('favourite_snack') # Removes item from dictionary.# Dictionary Comprehension
{key: valueforkey, valueinnew_dict.items() ifkey=='age'orkey=='name'} # {'name': 'Andrei', 'age': 32} --> Filter dict by keysLike lists, but they are used for immutable thing (that don't change)
my_tuple= ('apple','grapes','mango', 'grapes')
apple, grapes, mango, grapes=my_tuple# Tuple unpackinglen(my_tuple) # 4my_tuple[2] # mangomy_tuple[-1] # 'grapes'# Immutabilitymy_tuple[1] ='donuts'# TypeErrormy_tuple.append('candy')# AttributeError# Methodsmy_tuple.index('grapes') # 1my_tuple.count('grapes') # 2# Ziplist(zip([1,2,3], [4,5,6])) # [(1, 4), (2, 5), (3, 6)]# unzipz= [(1, 2), (3, 4), (5, 6), (7, 8)] # Some output of zip() functionunzip=lambdaz: list(zip(*z))
unzip(z)Unorderd collection of unique elements.
my_set=set()
my_set.add(1) # {1}my_set.add(100)# {1, 100}my_set.add(100)# {1, 100} --> no duplicates!new_list= [1,2,3,3,3,4,4,5,6,1]
set(new_list) # {1, 2, 3, 4, 5, 6}my_set.remove(100) # {1} --> Raises KeyError if element not foundmy_set.discard(100) # {1} --> Doesn't raise an error if element not foundmy_set.clear() # {}new_set= {1,2,3}.copy()# {1,2,3}set1= {1,2,3}
set2= {3,4,5}
set3=set1.union(set2) # {1,2,3,4,5}set4=set1.intersection(set2) # {3}set5=set1.difference(set2) # {1, 2}set6=set1.symmetric_difference(set2)# {1, 2, 4, 5}set1.issubset(set2) # Falseset1.issuperset(set2) # Falseset1.isdisjoint(set2) # False --> return True if two sets have a null intersection.# Frozenset# hashable --> it can be used as a key in a dictionary or as an element in a set.<frozenset>=frozenset(<collection>)None is used for absence of a value and can be used to show nothing has been assigned to an object
type(None) # NoneTypea=None==# equal values!=# not equal># left operand is greater than right operand<# left operand is less than right operand>=# left operand is greater than or equal to right operand<=# left operand is less than or equal to right operand<element>is<element># check if two operands refer to same object in memory1<2and4>1# True1>3or4>1# True1isnot4# TruenotTrue# False1notin [2,3,4]# Trueif<conditionthatevaluatestoboolean>:
# perform action1elif<conditionthatevaluatestoboolean>:
# perform action2else:
# perform action3my_list= [1,2,3]
my_tuple= (1,2,3)
my_list2= [(1,2), (3,4), (5,6)]
my_dict= {'a': 1, 'b': 2.'c': 3}
fornuminmy_list:
print(num) # 1, 2, 3fornuminmy_tuple:
print(num) # 1, 2, 3fornuminmy_list2:
print(num) # (1,2), (3,4), (5,6)fornumin'123':
print(num) # 1, 2, 3foridx,valueinenumerate(my_list):
print(idx) # get the index of the itemprint(value) # get the valuefork,vinmy_dict.items(): # Dictionary Unpackingprint(k) # 'a', 'b', 'c'print(v) # 1, 2, 3while<conditionthatevaluatestoboolean>:
# actionif<conditionthatevaluatestoboolean>:
break# break out of while loopif<conditionthatevaluatestoboolean>:
continue# continue to the next line in the block# waiting until user quitsmsg=''whilemsg!='quit':
msg=input("What should I do?")
print(msg)range(10) # range(0, 10) --> 0 to 9range(1,10) # range(1, 10)list(range(0,10,2))# [0, 2, 4, 6, 8]fori, elinenumerate('helloo'):
print(f'{i}, {el}')
# 0, h# 1, e# 2, l# 3, l# 4, o# 5, ofromcollectionsimportCountercolors= ['red', 'blue', 'yellow', 'blue', 'red', 'blue']
counter=Counter(colors)# Counter({'blue': 3, 'red': 2, 'yellow': 1})counter.most_common()[0] # ('blue', 3)- Tuple is an immutable and hashable list.
- Named tuple is its subclass with named elements.
fromcollectionsimportnamedtuplePoint=namedtuple('Point', 'x y')
p=Point(1, y=2)# Point(x=1, y=2)p[0] # 1p.x# 1getattr(p, 'y') # 2p._fields# Or: Point._fields #('x', 'y')fromcollectionsimportnamedtuplePerson=namedtuple('Person', 'name height')
person=Person('Jean-Luc', 187)
f'{person.height}'# '187''{p.height}'.format(p=person)# '187'- Maintains order of insertion
fromcollectionsimportOrderedDict# Store each person's languages, keeping # track of who responded first.programmers=OrderedDict()
programmers['Tim'] = ['python', 'javascript']
programmers['Sarah'] = ['C++']
programmers['Bia'] = ['Ruby', 'Python', 'Go']
forname, langsinprogrammers.items():
print(name+'-->')
forlanginlangs:
print('\t'+lang)Splat (*) expands a collection into positional arguments, while splatty-splat (**) expands a dictionary into keyword arguments.
args= (1, 2)
kwargs= {'x': 3, 'y': 4, 'z': 5}
some_func(*args, **kwargs) # same as some_func(1, 2, x=3, y=4, z=5)Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.
defadd(*a):
returnsum(a)
add(1, 2, 3) # 6deff(*args): # f(1, 2, 3)deff(x, *args): # f(1, 2, 3)deff(*args, z): # f(1, 2, z=3)deff(x, *args, z): # f(1, 2, z=3)deff(**kwargs): # f(x=1, y=2, z=3)deff(x, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3)deff(*args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)deff(x, *args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)deff(*args, y, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3)deff(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)[*[1,2,3], *[4]] # [1, 2, 3, 4]
{*[1,2,3], *[4]} # {1, 2, 3, 4}
(*[1,2,3], *[4]) # (1, 2, 3, 4)
{**{'a': 1, 'b': 2}, **{'c': 3}}# {'a': 1, 'b': 2, 'c': 3}head, *body, tail= [1,2,3,4,5]# lambda: <return_value># lambda <argument1>, <argument2>: <return_value># Factorialfromfunctoolsimportreducen=3factorial=reduce(lambdax, y: x*y, range(1, n+1))
print(factorial) #6# Fibonaccifib=lambdan : nifn<=1elsefib(n-1) +fib(n-2)
result=fib(10)
print(result) #55<list>= [i+1foriinrange(10)] # [1, 2, ..., 10]<set>= {iforiinrange(10) ifi>5} # {6, 7, 8, 9}<iter>= (i+5foriinrange(10)) # (5, 6, ..., 14)<dict>= {i: i*2foriinrange(10)} # {0: 0, 1: 2, ..., 9: 18}output= [i+jforiinrange(3) forjinrange(3)] # [0, 1, 2, 1, 2, 3, 2, 3, 4]# Is the same as:output= []
foriinrange(3):
forjinrange(3):
output.append(i+j)# <expression_if_true> if <condition> else <expression_if_false>
[aifaelse'zero'forain [0, 1, 0, 3]] # ['zero', 1, 'zero', 3]fromfunctoolsimportreducelist(map(lambdax: x+1, range(10))) # [1, 2, 3, 4, 5, 6, 7, 8, 9,10]list(filter(lambdax: x>5, range(10))) # (6, 7, 8, 9)reduce(lambdaacc, x: acc+x, range(10)) # 45any([False, True, False])# True if at least one item in collection is truthy, False if empty.all([True,1,3,True]) # True if all items in collection are trueWe have a closure in Python when:
- A nested function references a value of its enclosing function and then
- the enclosing function returns the nested function.
defget_multiplier(a):
defout(b):
returna*breturnout>>>multiply_by_3=get_multiplier(3)
>>>multiply_by_3(10)
30- If multiple nested functions within enclosing function reference the same value, that value gets shared.
- To dynamically access function's first free variable use
'<function>.__closure__[0].cell_contents'.
If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or a 'nonlocal'.
defget_counter():
i=0defout():
nonlocalii+=1returnireturnout>>>counter=get_counter()
>>>counter(), counter(), counter()
(1, 2, 3)if__name__=='__main__': # Runs main() if file wasn't imported.main()import<module_name>from<module_name>import<function_name>import<module_name>asmfrom<module_name>import<function_name>asm_functionfrom<module_name>import*In this cheatsheet '<collection>' can also mean an iterator.
<iter>=iter(<collection>)
<iter>=iter(<function>, to_exclusive) # Sequence of return values until 'to_exclusive'.<el>=next(<iter> [, default]) # Raises StopIteration or returns 'default' on end.Convenient way to implement the iterator protocol.
defcount(start, step):
whileTrue:
yieldstartstart+=step>>>counter=count(10, 2)
>>>next(counter), next(counter), next(counter)
(10, 12, 14)A decorator takes a function, adds some functionality and returns it.
@decorator_namedeffunction_that_gets_passed_to_decorator():
...Example Decorator: timing performance using a decorator.
- The functools decorator
@functools.wrapsis used to maintain function naming and documentation of the function within the decorator.
fromtimeimporttimeimportfunctoolsdefperformance(func):
@functools.wraps()defwrapper(*args, **kwargs):
t1=time()
result=func(*args, **kwargs)
t2=time()
print(f"Took: {t2-t1} ms")
returnresultreturnwrapper# calling a function with the decorator@performancedeflong_time():
print(sum(i*iforiinrange(10000)))Decorator that prints function's name every time it gets called.
fromfunctoolsimportwrapsdefdebug(func):
@wraps(func)defout(*args, **kwargs):
print(func.__name__)
returnfunc(*args, **kwargs)
returnout@debugdefadd(x, y):
returnx+y- Wraps is a helper decorator that copies metadata of function add() to function out().
- Without it
'add.__name__'would return'out'.
User defined objects are created using the class keyword
class<name>:
age=80# Class Object Attributedef__init__(self, a):
self.a=a# Object Attribute@classmethoddefget_class_name(cls):
returncls.__name__classPerson:
def__init__(self, name, age):
self.name=nameself.age=ageclassEmployee(Person):
def__init__(self, name, age, staff_num):
super().__init__(name, age)
self.staff_num=staff_numclassA: passclassB: passclassC(A, B): passMRO determines the order in which parent classes are traversed when searching for a method:
>>>C.mro()
[<class'C'>, <class'A'>, <class'B'>, <class'object'>]try:
5/0exceptZeroDivisionError:
print("No division by zero!")whileTrue:
try:
x=int(input('Enter your age: '))
exceptValueError:
print('Oops! That was no valid number. Try again...')
else: # code that depends on the try block running successfully should be placed in the else block.print('Carry on!')
breakraiseValueError('some error message')try:
raiseKeyboardInterruptexcept:
print('oops')
finally:
print('All done!')importsysscript_name=sys.argv[0]
arguments=sys.argv[1:]Opens a file and returns a corresponding file object.
<file>=open('<path>', mode='r', encoding=None)'r'- Read (default).'w'- Write (truncate).'x'- Write or fail if the file already exists.'a'- Append.'w+'- Read and write (truncate).'r+'- Read and write from the start.'a+'- Read and write from the end.'t'- Text mode (default).'b'- Binary mode.
<file>.seek(0) # Moves to the start of the file.<str/bytes>=<file>.readline() # Returns a line.<list>=<file>.readlines() # Returns a list of lines.<file>.write(<str/bytes>) # Writes a string or bytes object.<file>.writelines(<list>) # Writes a list of strings or bytes objects.- Methods do not add or strip trailing newlines.
defread_file(filename):
withopen(filename, encoding='utf-8') asfile:
returnfile.readlines() # or read()forlineinread_file(filename):
print(line)defwrite_to_file(filename, text):
withopen(filename, 'w', encoding='utf-8') asfile:
file.write(text)defappend_to_file(filename, text):
withopen(filename, 'a', encoding='utf-8') asfile:
file.write(text)importcsvdefread_csv_file(filename):
withopen(filename, encoding='utf-8') asfile:
returncsv.reader(file, delimiter=';')defwrite_to_csv_file(filename, rows):
withopen(filename, 'w', encoding='utf-8') asfile:
writer=csv.writer(file, delimiter=';')
writer.writerows(rows)importjson<str>=json.dumps(<object>, ensure_ascii=True, indent=None)
<object>=json.loads(<str>)defread_json_file(filename):
withopen(filename, encoding='utf-8') asfile:
returnjson.load(file)defwrite_to_json_file(filename, an_object):
withopen(filename, 'w', encoding='utf-8') asfile:
json.dump(an_object, file, ensure_ascii=False, indent=2)importpickle<bytes>=pickle.dumps(<object>)
<object>=pickle.loads(<bytes>)defread_pickle_file(filename):
withopen(filename, 'rb') asfile:
returnpickle.load(file)defwrite_to_pickle_file(filename, an_object):
withopen(filename, 'wb') asfile:
pickle.dump(an_object, file)fromtimeimporttimestart_time=time() # Seconds since
...
duration=time() -start_timefrommathimporte, pifrommathimportcos, acos, sin, asin, tan, atan, degrees, radiansfrommathimportlog, log10, log2frommathimportinf, nan, isinf, isnanfromstatisticsimportmean, median, variance, pvariance, pstdevfromrandomimportrandom, randint, choice, shufflerandom() # random float between 0 and 1randint(0, 100) # random integer between 0 and 100random_el=choice([1,2,3,4]) # select a random element from listshuffle([1,2,3,4]) # shuffles a list- Module 'datetime' provides 'date'
<D>, 'time'<T>, 'datetime'<DT>and 'timedelta'<TD>classes. All are immutable and hashable. - Time and datetime can be 'aware'
<a>, meaning they have defined timezone, or 'naive'<n>, meaning they don't. - If object is naive it is presumed to be in system's timezone.
fromdatetimeimportdate, time, datetime, timedeltafromdateutil.tzimportUTC, tzlocal, gettz<D>=date(year, month, day)
<T>=time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)
<DT>=datetime(year, month, day, hour=0, minute=0, second=0, ...)
<TD>=timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
minutes=0, hours=0, weeks=0)- Use
'<D/DT>.weekday()'to get the day of the week (Mon == 0). 'fold=1'means second pass in case of time jumping back for one hour.
<D/DTn>=D/DT.today() # Current local date or naive datetime.<DTn>=DT.utcnow() # Naive datetime from current UTC time.<DTa>=DT.now(<tz>) # Aware datetime from current tz time.<tz>=UTC# UTC timezone.<tz>=tzlocal() # Local timezone.<tz>=gettz('<Cont.>/<City>') # Timezone from 'Continent/City_Name' str.<DTa>=<DT>.astimezone(<tz>) # Datetime, converted to passed timezone.<Ta/DTa>=<T/DT>.replace(tzinfo=<tz>) # Unconverted object with new timezone.importre<str>=re.sub(<regex>, new, text, count=0) # Substitutes all occurrences.<list>=re.findall(<regex>, text) # Returns all occurrences.<list>=re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.<Match>=re.search(<regex>, text) # Searches for first occurrence of pattern.<Match>=re.match(<regex>, text) # Searches only at the beginning of the text.<str>=<Match>.group() # Whole match.<str>=<Match>.group(1) # Part in first bracket.<tuple>=<Match>.groups() # All bracketed parts.<int>=<Match>.start() # Start index of a match.<int>=<Match>.end() # Exclusive end index of a match.Expressions below hold true for strings that contain only ASCII characters. Use capital letters for negation.
'\d'=='[0-9]'# Digit'\s'=='[ \t\n\r\f\v]'# Whitespace'\w'=='[a-zA-Z0-9_]'# AlphanumericInspired by: https://github.com/aneagoie/ztm-python-cheat-sheet