Minimal Python Cheatsheet ========================= Main ---- ``` if __name__ == '__main__': main() ``` Ranges ------ ```python range(, , ) # Negative step for backward. [::] # Negative step for backward. random.randint(, ) ``` Dictionary ---------- ``` .items() .get(, ) .setdefault(, ) ``` Enumerate --------- ``` for i, in enumerate() ``` Inline ------ ### For ```pythonstub [i+j for i in range(10) for j in range(10) if i+j > 5] ``` ### Lambda ``` lambda , : ``` String ------ ### Print ``` print(, , end='', sep='', file=) ``` ### Regex ``` import re re.sub(, , ) re.search(, ) ``` ### Format ``` {:} -> ' ' {:>} -> ' ' {:^} -> ' ' {:_} -> '____' {:.} -> '' {:.} -> ' ' {:.f} -> ' 3.14' ``` Infinity -------- ``` float("inf") ``` 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() ``` Random ------ ``` import random random.random() random.shuffle() ``` Datetime -------- ``` import datetime now = datetime.datetime.now() now.strftime('%Y%m%d') now.strftime('%Y%m%d%H%M%S') ``` System ------ ### Arguments ``` import sys sys.argv ``` ### Read ``` with open(, encoding='utf-8') as file: return file.readlines() ``` ### Write ``` with open(, 'w', enconding='utf-8') as file: file.write() ``` ### Execute Command ``` import os os.popen().read() ``` JSON ---- ``` import json ``` ### Read ``` with open(, encoding='utf-8') as file: return json.load(file) ``` ### Write ``` 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() ```