Python Cheatsheet

Python

Timeit

from

start

python seconds = time.time() print("Seconds since epoch =", seconds)

`python import time

seconds passed since epoch

seconds = 1545925769.9618232 local_time = time.ctime(seconds) print(“Local time:”, local_time) `

Iteration

Helpful read

Get unique list

python mylist = list(set(mylist)) python sorted([*{*c}])

Regex BETWEEN two STRINGS

(?<=% of )(.*)(?= at ) example

`python import requests

img_data = requests.get(image_url).content with open(‘image_name.jpg’, ‘wb’) as handler: handler.write(img_data) `

Markdown to word doc

pandoc -o output.docx -f markdown -t docx HW5_pretty.md

Regex, characters between symbols § and ;

(?<=§).*?(?=;)

SO link

Regex find all between quotes

re.findall(r'"([^"]*)"', inputString)

SO 1 SO 2

Regex stripping multiple characters

import re
name = "Barack (of Washington)"
name = re.sub('[\(\)\{\}<>]', '', name)
print(name)
# OUTPUT: Barack of Washington

Stack Overflow

Using .format()

# different datatypes can be used in formatting 
print ("Hi ! My name is {} and I am {} years old"
                            .format("Daniel", 30)) 
# OUTPUT: Hi ! My name is Daniel and I am 30 years old

Ternary (why can’t I remember this)

condition_if_true if condition else condition_if_false

stack overflow about removing things

s = 'abc.com/abs'
exclude = '/'
s = ''.join(ch for ch in s if ch not in exclude)