Python and Libraries Cheatsheet =============================== Main ---- ``` if __name__ == '__main__': main() ``` Range ----- ``` range() range(, ) range(, , ) # Negative step for backward ``` List ---- ``` [::] .extend() .sort() .reverse() sum() ``` Dictionary ---------- .items() .get(, ) .setdefault(, ) ``` Set --- ``` = set() .add() .update() .union() .intersection() .difference() ``` Enumerate --------- ``` for i, in enumerate() ``` Type ---- ``` type() is int/str/set/list ``` ``` import numbers isinstance(, numbers.Number) ``` String ------ ``` str.replace(, , ) .isnumeric() ``` ### Print ``` print(, , end='', sep='', file=) ``` ### Regex ``` import re re.sub(, , ) re.search(, ) ``` ### Format ``` '{}'.format() ``` ``` {:} -> ' ' {:>} -> ' ' {:^} -> ' ' {:_} -> '____' {:.} -> '' {:.} -> ' ' {:.f} -> ' 3.14' ``` ### Text Wrap ``` import textwrap textwrap.wrap(, ) ``` Random ------ ``` import random random.random() random.randint(, ) random.shuffle() ``` Infinity -------- ``` float("inf") ``` Datetime -------- ``` import datetime now = datetime.datetime.now() now.strftime('%Y%m%d') now.strftime('%Y%m%d%H%M%S') ``` Inline ------ ### For ``` [i+1 for i in range(10)] [i+1 for i in range(10) if i > 5] [i+j for i in range(10) for j in range(10)] ``` ### Lambda ``` lambda , : lambda: ``` Class ----- ### Class ``` class : def __init__(self, ): self.a = def __repr__(self): return str({'a': self.a}) def __str__(self): return str(self.a) ``` ### Enum ---- ``` import enum class (enum.Enum): = ``` ### Copy ``` import copy copy.copy() copy.deepcopy() ``` System ------ ### Arguments ``` import sys sys.argv ``` ### Read File ``` with open(, encoding='utf-8') as file: return file.readlines() ``` ### Write to File ``` with open(, 'w', enconding='utf-8') as file: file.write() ``` ### Execute Command ``` import os os.popen().read() ``` JSON ---- ``` import json ``` ### Read File ``` with open(, encoding='utf-8') as file: return json.load(file) ``` ### Write to File ``` with open(, 'w', enconding='utf-8') as file: file.write(json.dumps()) ``` SQLite ------ ``` import sqlite3 db = sqlite3.connect() ``` ### Read ``` cursor = db.execute() if cursor: cursor.() db.close() ``` ### Write ``` db.execute() db.commit() ``` Threading --------- ``` import threading ``` ### Thread ``` thread = threading.Thread(target=, args=(, )) thread.start() thread.join() ``` ### Lock ``` lock = threading.Rlock() lock.acquire() lock.release() ```