© 2019 Martin Bruchanov, bruchy@gmail.com
Set of interpreter:#!/usr/bin/env python # everything behind hash""" more lines comment """
python options script.py – run script filename-V – print version-c 'code' – run code from command linepython -m py_compile script.py – test syntax of scriptpython3 -c 'import keyword; print(keyword.kwlist)' – keywordspython -i, ipython – interactive modepython -m virtualenv /path/to/dir or python3 -m venvsource /path/to/dir/bin/activatepip –versiondeactivate| FOR cycle | WHILE contition |
|
for identifier in list : ␣␣␣␣list-processing code [ else : ␣␣␣␣suite ] |
while condition ␣␣␣␣repeat if condition is true [ else: ␣␣␣␣suite ] |
| IF-THEN-ELSE | TRY block |
|
if condition : ␣␣␣␣true suite [ elif condition: ␣␣␣␣else if true ] [ else : ␣␣␣␣else suite ] |
try: ␣␣␣␣possible runtime error except [type [as value]]: ␣␣␣␣error-recovery code [ else: ␣␣␣␣suite ] [ finally: ␣␣␣␣suite ] |
import module – find and initialize modulefrom module import * – import all to local name spaceimport module as name – rename imported modulefrom module import name as othernamebreak – exit while or for loop, skip associated elsecontinue – perform next iteration of cyclequit([code=exit code]) – exit script and set return valueraise Exception('Message') – create error during executionglobal name – reference global valueexec("print('Ahoj')") – compile and exec codewith expression [as variable]:
␣␣␣␣suite – block entry actionspass – do-nothing placeholder statementdel name, del name[i], del name[i:j:k], del name.attibute – delete variables, items, keys, attributesassert expression [, message]exec codestringresult expr. for loop var. in iterable if filter expr.s = 'Yes' if k == True else 'No' – ternary operatordef noop(*args, **kws): return None – no-operation functionclass Name:
␣␣␣␣suite_private – underscored named object is privatedef __init__(self, ...):self.data = [] – constructorclass DerivedClass(BaseClass) – inheritancedef function(param1, param2,...):
␣␣␣␣passdef func(arg,... arg=value, ... *arg, **arg):
arg – matched by name or positionarg=value – default value if arg is not passed*arg – collect extra positional args as a new tuple**arg – collect extra positional args as a new dictionarylambda args1 : expression – anonymous function makermap(lambda x: x.capitalize(), ['abc','def']) – examplereturn [expression] – return from functionyield expression – suspend function state and return, on next iteration restore prior statedef gen(x):\n for i in range(x): yield i*i – returns gener. objectvariable = 12 – assign valuetype(variable) – return type of variableglobal name [,name] – global variable in local context2006, 2006l, 2006L – decimal integer, long;0775, oct(0x1fd) – octal;0xBABE, hex(47806) – hexadecimal;0b101010, bin(42) – binary;3.14, 314e-2 – floating point;1+2j, 1.0+2.0J, complex(1,2) – complex number;b'Ahoj' – sequence of 8-bit values;int(x), long(x), float(x), str(n) – type conversionsint('GEEK', 21) – convert string number with given basec=1+2j; c.conjugate(), (1+2j).conjugate() – conjugate of complex number 1-2jabs(x) – absolute value of xround(x[,n]) – x rounded to n digits(10.5).as_integer_ratio() – returns tuple (21, 2)(255).bit_length() – number of digits of binaryX, Y = Y, X – swap values of X and Ya,b,c = range(3) – read list values, a=0,b=1,c=2vars(), globals(), locals() – return dictionary of variablessetattr(obj, 'b', c) is equivalent obj.b = cgetattr(obj, 'a') is equivalent obj.ahasattr(obj, name) – True if name is object atributeFalse, True – booleanNone – represents no valueor, and, not x – boolean operators| (or), ^ (xor), & (and), ~x (neg.) – binary operatorsX in Y, X not in Y – membership testsX is Y, X is not Y – same or different object<, <=, >, >=, <>, !=, == – comparisons*, /, //, % – multiply, divide, floor divide, remainderx << n, x >> n – bitwise shifts by n bitsx**y, pow(x,y) – power xy+= &= -= |= *= ^= /= >>= %= <<= **= //=divmod(x,y) – return tuple (x/y, x%y)| Function | Tuple | List | Dict. | String | Set |
|---|---|---|---|---|---|
| Init. | (,),tuple() | [], list() | , dict() | "",'',str() | , set() |
clear | — | — | ● | — | ● |
copy | — | — | ● | — | ● |
count | ● | ● | — | ● | — |
index | ● | ● | — | ● | — |
pop | — | ● | ● | — | ● |
remove | — | ● | — | — | ● |
update | — | — | ● | — | ● |
t = (), t = tuple() – create empty tuplet = (1, 2, 3) – like list, but can't change their valuest[1] – access second item, returns 2t.index(x [, i [, j]]) – return index of first occurrence of xt.count(x) – return number of item xl = [], l = list() – empty listl = [1, 2, 3] – one dimensional array[3] * 4 – repeated 4× to [3, 3, 3, 3]l[1] – returns 2, indexing: 10 21 32l[i:j] – slicing from index i to j-1l[i:] – slicing from index i to end of listl[i:j:k] – slicing with step k ≈ pprox l[slice(i,j[,k])]l[-1] – last item (first from back)0 in [1, 2, 3] – False, 1 in [1, 2, 3] Truel = range(5) – create list [0, 1, 2, 3, 4]l = range(start, stop[, step]) – given range with stepl = [x**2 for x in range(9)] – list from expression resultl.index(item) – return index of item in listl.count(item) – total number of occurrences of iteml = ["text", 12, 3, [1, 2]] – more types in one listl2d=[[1,2,3], [4,5,6], [7,8,9]] – two-dimensional listl2d[1][1] – returns 5list('abc') – returns list of chars ['a','b','c']len(l) – return length of listl.append(value) – add value to the listl.extend([4,5]), list[len(list):]=[4,5], list += [4,5] – append another listl.insert(i, x), list[i]=x – insert x at given indexl[:0]=[x,y,z] – insert item at front of listl.remove(value) – remove first occurrence of valuel.pop(i), l.pop() – return and remove value, without index lastl.index(x [, i[, j]]) – index of first occur. of x, between i to j-1l.count(x) – return number of occurrence of object xl.sort(key=None, reverse=False) – sort list in-placel.reverse() – reverse list in-placesum(l) – return sum of numeric listsorted(set(l)) – sort and unique list via setsorted(unsorted_l, key=str.casefold) – sort case insensitiveh = {}, h = dict() – initialization of empty dictionaryh = { "key1": "value", "key2": "another"} – definitionh = dict(key1="value", key2="another") – different syntaxh = dict([('key1', 'value'), ('key2', 'another']) – yet anotherh["key3"] = 333 – add another valueh[(1+2j)] = 666 – also hashable object can be a keyh = {c: ord(c) for c in 'spam'} – comprehension expression'key' in h – returns True if key exist (was h.has_key("key"))h.keys(), h.values() – return list of keys, and valuesh.clear() – remove all itemsg = h.copy() – returns a shallow copy of hh.get(key [, default]) – if key is not found return defaulth.popitem() – removes and returns an (key, value) pairh.pop(k [, def]) – returns and removes k else return defdel h['key1'] – remove entry for key key1h.fromkeys(seq [, value]) – new dictionary from keys in seqdict(zip(['a','b'], [1,2])) – join to {'a': 1, 'b': 2}for key, value in h.items(): – iterate dictionaryg = {}; g.update(h), g = dict(h), g = dict(h.items()) – make copyA = set() – empty set A={ ∅ }A = set('Ouagadougou') = A = set(['a','d','g','o','u','O']), unordered collection of unique and immutable objectsA = {'a', 'd', 'g', 'o', 'u', 'O'} – set definitionA = frozenset(range(−5, 5)) – immutable set of -5…4'a' in A – returns True if value is presented a ∈ AA - B, A.difference(B) – new set contains difference A \ BA | B, A.union(B) – join two sets, no duplicates A ⋃ BA & B, A.intersection(B) – same items in both sets A ⋂ BA <= B, A.issubset(B) – returns True is A is subset of B A ⊂ BA >= B, A.issuperset(B) – is A superset of B? A ⊃ BA < B, A > B – true subset, superset A ⊂ B, A ⊃ BA ^ B, A.symmetric_difference(B) – A ∆ B = (A ⋃ B) \ (A ⋂ B)A |= B, A.update(B) – adds items in B to AA.discard(X) – remove item if existA.add(X), A.remove(X) – add, remove item from setA.clear() – remove all itemsA.pop() – remove and return arbitrary itemlen(A) – get number of items in Afor x in A: – all iteration contextB=A.copy(), B=set(A) – make copy of sets = "Hello", s = 'Hello' – definition, " and ' works sames[::-1] – reverse string (olleH)"""This is multi-line block""" – collects into a single strings[1]='e' – indexing H0 e1 l2 l3 o4s[i:j] – substring from i to j-1 (same indexing as lists)str(n) – convert number n to string'Hello ' + 'World', "Hello" "World" – concatenation'Hello' * 3 – repetition 3×"\u2192", "\U00002192", "\N{Rightwards Arrow}"r"\n", R'\n' does not interpret escape sequencesur"\n", UR'\n'str(), bytes(), bytearray() – create string from object\xhh, \ooo, \0 – hex, octal, null bytechr(65), unichr(65), ord('A') – returns character, ASCII codeeval(s) – convert and execute code given by stringexecfile(filename) – like eval, but for whole fileprint(*objects, sep=' ', end='\n', file=sys.stdout)'%s, %s, %.2f' % (13, 'txt', 22/7.0) – '13, txt, 3.14''{0}, {1}, {2:.2f}'.format(13,'txt',22/7.0) – other def."%(a)d %(b)s" % {"a":6, "b":"text"} – formating dictionary"{a} {b}".format(**{'a':1, 'b':2}) – formating dictionary"%*s" % (10, "text") – width given as parameter"%#x %#o" % (15,15) – prints number base prefixes"%+.*f" % (5, 22.0/7) – +3.14286, 5 digits after ‘.’%[(keyname)][flags][width][.precision]typecode-/+ left/right justify, 0/' ' zero/space fills – String (or any object, uses str())r, – s, but uses repr(), not str()c – Character (int or str)d, i, u – Decimal (base 10 integer)o – Octal (base 8 integer)x, X – Hex (base 16 integer)e, E – Floating-point exponentf, F – Floating-point decimalg, G – Floating-point e,f/E,f%% – Literal '%'{fieldname!conversionflag:formatspec}[[fill]align][sign][#][0][width][,][.prec][typecode]vprint = print if VERBOSE else lambda *a, **k: None – verbose printss.find/rfind(sub, [,s [,e]]) – index of first occur. of sub,s.index/rindex(sub [,s [,e]]) – ValueError if not founds.endswith/startswith(sub [,s [,e]]) – true if starts/endss.count(sub, [,s [,e]]) – get number of substringss.upper(), s.lower(), s.swapcase() – converts cases.split([sep [, maxsplit]) – return list of wordssep.join(iterable) – concatenates with separator' and '.join(['a', 'b', 'c']) – returns 'a and b and c's.replace(old, new [, count]) – replace old by news.splitlines(0/1) – split by '\n', 1 – keeps end chars.strip([chars]) – remove leading and trailing white spacess.lstrip, s.rstrip – just from left or right sides.center/ljust/rjust(width [,fill]) – justify strings.capitalize() / s.title() – make first/all word(s) uppercases.expandtabs(tabsize) – replaces tabs with spaces (default 8)isalnum, isalpha, isdecimal, isdigit, isidentifier, islower, isnumeric, isprintable, isspace, istitle, isupper – testshelp(object), help('function') – display documentationmax(iterable), min(iterable) – return max/min valuereversed(iterable) – return a reverse iteratorsorted(iterable, key=None, reverse=False) – return sortedsorted(lt, key=lambda x: x[1]) – sort list of tuples by 2nd elementenumerate(iterable, start=0) – return an enumerate objectall(iter), any(iter) – True if all/any of elements are/is true.hash(obj) – return hash value of objectiter(o [,sentinel]) – return an iterator objectnext(iterator [,default]) – return next item from iteratormap(function, iterable, ...) – apply function on every iteminput([prompt]) – read line for stdinfile=open('data.txt'[, 'mode']) – open, mode: r,w,rb,w,r+,w+s = file.read([n]) – read file of n bytes into string sfile.readline() – return line of file, empty at EOFfile.readlines() – read entire file into a list of line stringsfor line in file: – process file line by linefile.write(s) – write string s into fileprint >>file, "Output" – write string to filefile.writeline(list) – write all strings in list to filefile.close() – close to free resourcesfile.tell() – return file positionfile.seek(offset [, whence]) – set file positionfile.flush() – flushes file's bufferfile.truncate([size]) – truncate file to size bytesfile.fileno() – get file descriptor integerfile.closed, file.mode, file.name – return attributeswith open('file.txt', 'r') as f: – block with file manipulations(import re)ro=re.compile(pattern, flags=0) – create RegexObject ‘ro’re.DOTALL (S), re.IGNORECASE (I), re.LOCALE (L), re.MULTILINE (M), re.VERBOSE (X), re.UNICODE (U)re.match(pattern, string) – if match return MatchObjectre.search(pattern, string) – match regex anywhere in stringre.split(pattern,string) – split patternre.findall(pattern, string) – return substrings as listre.finditer(pattern, string) – return matches as iteratorre.sub(pattern, repl, string, count=0, flags=0) – return string with replaced patternre.subn(…) – return tuple (string, num. of replacements)re.escape(string) – string with escaped regex's metacharactersro.match, search, split, sub, subn, findall, finditerro.flags, ro.pattern – used argument for reg. obj. creationro.groups() – number of matched groupsro.group(n) – return nth string matched by regexro.start(), ro.end(), ro.span() – return starting, ending position or tuplesys.argv – CLI parameters, argv[0] name of scriptsys.stdin.readline() – read line from standard inputsubprocess.call(["ls", "-l"]) – execute system commandout = subprocess.check_output(['uname', '-a']) – store output of command to variablefilelist = subprocess.Popen("ls *", shell=True,
stdout=subprocess.PIPE).communicate()[0] – read data from pipeos.stat('/path/to/file.txt') – return POSIX stat file infoos.environ.get('PATH') – get value of environment variable PATH