0% acharam este documento útil (0 voto)
4 visualizações27 páginas

Python 1

Este documento é uma folha de dicas abrangente sobre Python, cobrindo uma variedade de tópicos como tipos de dados, controle de fluxo, funções e operadores. Ele inclui exemplos de código e explicações concisas para facilitar a referência rápida. O conteúdo é voltado para desenvolvedores que buscam um guia prático para a linguagem Python.
Direitos autorais
© All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF ou leia on-line no Scribd
0% acharam este documento útil (0 voto)
4 visualizações27 páginas

Python 1

Este documento é uma folha de dicas abrangente sobre Python, cobrindo uma variedade de tópicos como tipos de dados, controle de fluxo, funções e operadores. Ele inclui exemplos de código e explicações concisas para facilitar a referência rápida. O conteúdo é voltado para desenvolvedores que buscam um guia prático para a linguagem Python.
Direitos autorais
© All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF ou leia on-line no Scribd
Python Cheatsheet The “Best Python Cheat Sheet Tust what you need Botit-in (1) Execution (26) List (9) Set (10) Bytes (11) Flow control (5) Nunber (22) string (18) Class (12) Function (11) Operator (3) Test (26) debug (26) Generator (17) Regex (19) Time (23) Decorator (14) Irerator (16) Resource (26) tuple (8) Dictionary (9) Keyword (1) Scope (6) Types (26) Exception (24) Library (26) Sequence (7) and continue for match® True as def from None try assert del global nonlocal typed async elif if not while avait else import or with break except in pass yield case® False is raise 0 class finally Lambda return ®soft keywords abs (number) Absolute value of bytes(..) New bytes object from number byte-integers, aiter(async_iterable) Asynchronous iterator stringy bytes: for an asynchronous _calllable(object) True if object is iterable callable all(iterable) True if all elements chr(i) One character string of iterable are true for unicode ordinal 4 (all([]) is True) (0 <= 4 <= oxioffff) any(iterable) True if any element classmethod(func) ‘Transform function of iterable is true into class method (any({]) 4s False) compite(source, Compile source into ascii (object) A string with a code or AST object printable + complex(real=0, Complex number with representation of an smagaa) the value real + sujaet imag*1j bin(number) Convent nese delattr(object, name) Delete the named Conenec eaay attribute, if object sera allons bool (abject) Boolean value dict(-) Create new dictionary breakpoint(*args, Drop into debugger = = = stems) ae dir([object]) List of anes in the [Link](*a aeigag 8 ee object.__dir__() or E attributes bytearray(..) New array of bytes from byte-integers, string, bytes, object with buffer API Python 3.8+ | 2024 Jun 15 © [Link] 1 of 26 divmod(x, y) enumerate (iterable, start=6) eval (source, exec(source, globals=None, Jocals=None) filter (func, iterable) Float(: ) format (object, format_spec="') frozenset(..) getattr(object, name[, default]) globals() hasattr(object, name) hash( object) help(..) hex (number) id(object) --inport__(name, ..) input(prompt="') int(..) 2 of 26 The *Best Python Cheat Sheet Return (quotient x//y, remainder x%y) Enumerate object as (n, item) pairs with fn initialised to start value Execute Python expression, string or code object from compile() Execute Python statements, string or code object from compile() Iterator yielding items where func(item) is true, or bool(item) if func is None Floating point number from number or string Formatted representation New frozenset object Get value of named attribute of object, else default or raise exception Dictionary of current module namespace True if object has named attribute Hash value of object (see object .__hash__()) Built-in help system Convert integer to lowercase hexadecimal string Return unique integer identifier of object Invoked by the import statement Read string from stdin, with optional prompt Create integer from number or string isinstance(object, cls_or_tuple) issubclass(cls, cls_or_tuple) iter(object, .) len(object) list(.) locals() True if object is instance of given class(es) True if class is subclass of given class(es) Iterator for object Length of object Create list Dictionary of current local symbol table map(func, *iterables) Apply function to max(... key=func) memoryview(object) min(.., key=func) next(iterator[, default] ) object() ‘oct (number ) open(file, ..) ord(chr) pow(base, exp, mod=None) print(value, ..) property(..) range(..) repr(object) [Link] every item of iterable(s) Largest item of iterable or arguments, optional key function extracts value ‘Access internal object data via buffer protocol Smallest item of iterable or arguments, optional key function extracts value Next item from iterator, optionally return default instead of StopIteration New featureless object Convert integer to octal string Open file object Integer representing Unicode code point of character Return base to the power of exp Print object to text stream file Property decorator Generate integer sequence String representation of object for debugging Python 3.8+ | 2024 Jun 15 The *Best Python Cheat Sheet reversed(sequence) round(number , ndigits=None) Reverse iterator Number rounded to ndigits precision after decimal point set(..) New set object setattr(object, name, Set object attribute value) value by name slice(..) Slice object representing a set of indices sorted(iterable, New sorted list from key=None, the items in iterable statiomethod(func) Transform function into static method str(.) String description of object sum(iterable, Sums items of start=8) iterable, optionally adding start value super (..) Proxy object that delegates method calls to parent or sibling ‘tuple(iterable) Create a tuple type(..) Type of an object, or build new type Return object.__dict__ or locals() if no argument vars( [object]) Iterate over multiple iterables in parallel, strict requires equal length zip(*iterables, strict-False) Precedence (high->low) Cor) Lord ar} {tar} s[i] s[i:j] [Link] F(.) await x +k, -X, x try x*y, x@y, x/y, x//y, x%Y “x x+y, X= ¥ x>y xay Ag xly xy xeey OY oeEy Xeny xley xisy x is not y x ins x not ins not x x and y xory ~if else . Tambda Python 3.8+ | 2024 Jun 15 [Link] Description tuple, list, set, dict index, slice, attribute, function call await expression unary positive, negative, bitwise NOT power multiply, maxtrix multiply, divide, floor divide, modulus add, substract bitwise shift left, bitwise and bitwise exclusive or bitwise or right ‘comparison, identity, membership boolean negation boolean and boolean or conditional expression lambda expression assignment expression 3 of 26 The *Best Python Cheat Sheet Assignment Usually equivalent a= b Assign object b to label a ats b a=atb a-= b a=a-b at b a=a*b a/= b a= a/b (true division) a/i=b aza at b asa%b a tb asa**b aa b asaéb al= b a=alb at b a=sa*b ass b asa>>b a aza [x for i in z if (x:=i*#2) > 10] (16, 25] eine Unpack multiple values to a name using the splat operator. head, *body head, *body, tail s # assign first value of s to head, s # assign first and last values of s to head end tail, remainder remainder to body to body ‘body, tail = s # assign last value of s to tail, remainder to body s = [*iterable[, ..]] # unpack to list s = (#iterable[, ..]) # unpack to tuple s {*iterable[, ..]} # unpack to set d2.= (*di[, .]} # unpack to dict 4 of 26 © [Link] Python 3.8+ | 2024 Jun 15 The *Best Python Cheat Sheet Flow control for item in : [else # if loop completes without break while ; [else # Af loop completes without break break # immediately exit loop continue # skip to next loop iteration return{ value] # exit function, return value | None yield[ value] assert [, message] exit generator, yield value | None if not raise AssertionError({message]) Af : [elif : -l* [else if else with [ as name]: # context manager A with statement takes an object with special methods: m __enter__() - locks resources and optionally returns an object _exit_() - releases resources, handles any exception raised in the block, optionally suppressing it by returning True class AutoClose def __init__(self, filename) : [Link] = filename def __enter__(self): self.f = open(self. filename) return self.f def _exit__(self, exc_type, exception, traceback) self.f-close() >>> with open(‘[Link]', ‘w') as f: . [Link](‘Hello World! ") 35> with AutoClose('[Link]') as f: print([Link]()) Hello World! Python 3.8+ | 2024 Jun 15 © [Link] 5 of 26 The *Best Python Cheat Sheet match : case [ if ]: # conditional match, if “guard” clause case | : # OR pattern case # default case ‘Match case pattern 1/" abe" /True/None/math pi Value pattern, match literal or dotted name Capture pattern, match any object and bind to name - Wildcard pattern, match any object () Class pattern, match any object of that type ( | [| ~] Or pattern, match any of the patterns left to right [[, Napping pattern, match dictionary with matching *+kwds}]} items, may be nested as Bind match to name () Builtin pattern, shortcut for () as (e.g. str, int) ™Class patterns ™ Do not create a new instance of the class m Accept positional parameters if class defines __match_args__ special attribute (e.g. dataclass) m Sequence patterns support assignment unpacking m Names bound in a match statement are visible after the match statement Scope levels: Builtin Nanes pre-assigned in Funetion (local) Names defined in current builtins module funetion Module (global) Names defined in current by defeule. hes: read-only ee access to module and hall th USbRY Stone enclosing function nares cannot access local Ucar cmccoan ees creates a new local name variables global grants Enclosing Names defined in any read/write eccess ta (closure) enclosing functions specified module name nonlocal grants read/write access to specified name in closest enclosing function defining that name Generator Names contained within expression generator expression 6 of 26 © [Link] Python 3.8+ | 2024 Jun 15 The *Best Python Cheat Sheet Comprehension Names contained within Instance comprehension Class Names shared across all Method instances m globals() - return dict of module scope variables ™ Iocals() - return dict of local scope variables >>> global_name >>> def read_global() print(global_name) vs. local_name = "only available in this function" >>> read_global() >>> def write_global(): . global global_name on global_name = 2 >>> write_global() >> print(global_name) >> def write-nonocs](): closure_name s.. def nested(): a nonlocal closure_name closure_name = 2 nested() . print(closure_name) 25> write_nonlocal() Names contained within a specific instance Names contained within a specific instance method class C: class_name = 1 def init__(self): self instance_name = 2 def method(self) : self.instance_name = 3 C.class_name = 3 method_name = 1 Sete Operations on sequence types (Bytes, List, Tuple, String) xins True if any s[i] == x s-index(xf, x not ins True if no sli] == x start[, stop)]) si + s2 Concatenate s1 and 2 FavrSaLET s*nn*s Concatenate n copies of s [Link](x) Count of sfi] == x len(s) Count of items sorted(s, cmp=fune, min(s) Smallest item Iceyagettan, max(s) Largest item reverse=False) Select items from sequence by index or slice. Python 3.8+ | 2024 Jun 15 © [Link] Smallest i where s[i] x, start/stop bounds search Tterator ons in reverse order (for string reversed(list(s))) New sorted list 7 of 26 The *Best Python Cheat Sheet >>> s = [8, 1, 2, 3, 4] >>> sla] ¥ Q-based indexing @ >>> s[-1] # negative indexing from end 4 a>» s[slice(2)] # slice(stop) - index from @ until stop (exclusive) (a, 1] >>> s[slice(1, 5, 3)] # slice(start, stop[, step]) - index from start to stop (exclusive), with optional step size (+|-) (1, 41 253 s[:2] # slices are created implicitly when indexing with [start :stop:step] {e, 1] >>> s[3::-1] # negative step (3, 2, 1, 6] o> s[1:3] M1, 2] o> s[1:5:2] 1, 3] WA sortable class should define _eq__(), 1t__(), special methods. MWith functools @total_ordering decorator @ class need only provide _eq..() and one other comparison special method. m Sequence comparison: values are compared in order until a pair of unequal values is found. The comparison of these two values is then returned. If all values are equal, the shorter sequence is lesser. gt_(), --le__() and __ge__() from functools import total_ordering @total_ordering class C: def _init__(self, a): self.a= a def _eq__(self, other): isinstance(other, type(self)): return self.a == other.a return NotImplemented It__(self, other): isinstance(other, type(self)): return self.a < other.a return NotImplenented def Inmutable hashable sequence. a2, ‘a, 3.8) Create tuple s=1,'a', 3.0 s= (1,) Single-item tuple s= 0 Empty tuple G, 2, 3) == (1, 2) + (8,) ‘Add makes new tuple a (1, 2) *2 Multiply makes new tuple 8 of 26 © [Link] Python 3.8+ | 2024 Jun 15 The *Best Python Cheat Sheet Tuple subclass with named items. Also [Link]. >>> from collections import namedtuple >>> Point = namedtuple(‘Point’, ('x', ‘y')) # or namedtuple( ‘Point’, ‘x y') >>> p = Point(1, y=2) Point(x=1, y=2) >>> pla] 1 >>> py 2 Mutable non-hashable sequence Create list [Link](it) Add items from iterable s[len(s):1en(s)] to end zit Aistirange($)) [Link](i, x) Insert item at index i si] = x Replace item index i with s[izi] = [x] x [Link](x) Remove first item where s[] = it Replace slice with del sli] == x iterable s[[Link](x)] del s[] Remove slice y = [Link]([i]) Remove and return last s[] = [] item or indexed item [Link](x) ‘Add item to end [Link]() Reverse items in place st x . [Link](cmp=fune, Sort items in place, arpete) ented key=getter, default ascending reverse=False) result = [ for item in { if } {for item2 in { if } .. for itemN in { if }}] # is equivalent to: result = [] for item! in : for item2 in : for itemN in : Af and .. and result .append() Mutable non-hashable key:velue pair mapping. dict() Empty dict dict (**kwds) Create from keyword } arguments dict() pairs values)) of keys and values ('d' 24, ‘a 22} Python 3.8+ | 2024 Jun 15 © [Link] 9 of 26 The *Best Python Cheat Sheet [Link](keys, Create from keys, all [Link](key) value=None) set to value [Link]() Iterable of keys [Link]() Tterable of values 4-Popitem() 4. items() Tterable of (key, value) pairs aaa [Link](key, Get value for key, or default=None) default -copy() [Link](key, Get value for key, nee aa default=None) add if missing e-d | 2a a3 = {**d1, **d2} Remove and return value for key, raise KeyError if missing Remove and return (key, value) pair (last-in, first-out) Remove all items Shallow copy ‘Add/replace key:value pairs from d2 to di Merge to new dict, d2 trumps di # defaultdict() sets default value returned by callable() import collections [Link] (lambda: 42) # dict with default value 42 Di eee # {k: v for k, v in [ if ]} poo {xi x**2 for x in (2, 4, 6) if x < 5} (2: 4, 4: 16) Mutable (set) and immutable (frozenset) sets. set() Empty set [Link]() [mutable] {1, 2, 3} Create (note: {} [Link](s2[, creates empty dict - s3-]) sad!) s1 8 s2 set(iterable) Create from iterable s1.intersection_updat {#iterable} e(s2) [mutable] frozenset(iterable=No Create frozen set [Link](s2[, s3.]) ne) st | s2 Ten(s) Cardinality [Link](s2[, vins Test membership v not ins z s1.difference_update( s1issubset(s2) Teve af st is subset i "fautabtel [Link](s2) True if si is ut sayeueetriogdirteran superset of <2 ce(s2) sl 52 [Link](v) [mutable] Add elenent 1 eymmeicie differen [Link](v) [mutable] Remove element ce_update(s2) (KeyError if not [mutable] discard(v) sates ‘lement if eae [Link](v jenove element i s : [Link](iti[, it2..]) [mutable] present oe [Link]() [mutable] Remove and return arbitrary element (KeyError if empty) Remove all elements New set of shared elements Update elements to intersection with s2 New set of all elements New set of elements unique to st Remove elements intersecting with s2 New set of unshared elements Update elements to symmetric difference with s2 Shallow copy Add elements from iterables 10 of 26 © [Link] Python 3.8+ | 2024 Jun 15 The *Best Python Cheat Sheet ncn # {x for x in [ if ]} se {x for x in ‘abracadabra’ if x not in ‘abo'} Cr, 'd'} Immutable sequence of bytes. Mutable version is bytearray. biestr>' Create from ASCII characters and \x@0-\xff bytes() Create from int sequence bytes(, Create from string ‘utf-8") .encode( ‘ut £8") .to_bytes(1 Create from int ength, order, (order='big'| little’) signed=False) bytes. fromhex('< Create from hex pairs hex>') (can be separated by whitespace) = Return int in range 6 to [] 255 xbytes> = [] List () .join () str(, ‘utf-8") .decode(' utf-8") int.from_bytes(b ytes, order, signed=False) .hex(sep= ) bytes_per_sey Return bytes even if only one element Return ints in range @ to 255 Join byte_objs sequence with bytes_sep separator Convert bytes to string Return int from bytes (order='big'|' little’) Return hex pairs def read_bytes( filename) : with open(filename, ‘rb') as f: return [Link]() def write_bytes(filename, bytes_obj): with open(filename, ‘wb') as f .write(bytes_obj) Python 3.8+ | 2024 Jun 15 © [Link] 11 of 26 The *Best Python Cheat Sheet Funel del # var-positional def f(*args): ~ # #1, 2) def f(x, *args): — # £(1, 2) def f(#args, 2): = # (1, 222) # var-keyword def F(**kwds) : def f(x, **kwds): def f(#args, **kwds): def f(x, *args, **kwds): y 1 FG, 2) + ye2, 223) | F(1, 2, 223) | FC, 2 3) def f(*args, y, **kwds): ~ # f(x=1, y=2, 263) | f(1, y=2, 2-3) # positional-only before / def f(x, 7, y): # £(1, 2) | FC. y=2) def f(x,y, /)t = # (1, 2) # keyword-only after * def F(x, *, y) def F(*, x, y) nr args = (1, 2) #* expands sequence to positional arguments kwds = {'x': 3, ‘y': 4} # ** expands dictionary to keyword arguments fune(*args, **kwds) # is the same as: func(1, 2, x=3, y=4) Cas class C: ""*Class docstring. def __init__(self, a): "Method docstring. self.a=a repr__(self): Ised for repr(c), also for str(c) if _str__ not defined." return f' {self.__class_. ({[Link]}) def + €.9. print(c) return str(self.a) @classmethod def get_class_name(cls): # passed class rather than instance return cls.__name__ @staticmethod def static(): # passed nothing return 1 >>> ¢ = C(2) # instantiate # under the covers, class instantiation does this obj = cls.__new__(cls, *args, **kwds) if isinstance(obj, cls): obj.--init__(*args, **kwds) 12 of 26 © [Link] Python 3.8+ | 2024 Jun 15 The *Best Python Cheat Sheet pe class C: @property def f(self): if not hasattr(self, ‘f° return return self._f ef setter def f(self, value): self. = value Operator self + other other + self self other self - other other - self self other self * other other * self self *= other self @ other other @ self self @= other self / other other / self self /= other self // other other // self self //= other self % other other % self. self %= other self ** other other ** self self **= other self << other other << self self <<= other self >> other other >> self. self >>= other self & other other & self self & other self | other other | self self |= other self * other other * self self = other divmod(self, other) divmod(self, other) Python 3.8+ | 2024 Jun 15 (self, ottien) -(self, other) (self, other) (self, other) -(self, other) “(self, other) (self, other) -(self, other) =(self, other) matmul__(self, other) -(self, other) (self, other) (self, other) rtruediv__(self, other) (self, other) --floordiv._(self, other) rfloordiv__(self, other) ifloordiv__(self, other) _-(self, other) _(self, other) (self, other) (self, other) (self, other) self, other) (self, other) ilshift__(self, other) rshift__(self, other) _crrshift__(self, other) irshift__(self, other) and__(self, other) Trand__(self, other) =(self, other) (self, other) =-ror__(self, other) —ior__(self, other) _-xor__(self, other) “rxor__(self, other) ixor__(self, other) divmod__(self, other) rdivmod__(self, other) © [Link] 13 of 26 The *Best Python Cheat Sheet Operator Method -self -—neg__(self) +self --pos__(self) abs(self) _(self) ~self ~-invert__(self) [bitwise] self == other ~-eq__(self) [default ‘is', requires —hash__] self != other = self < other _-It_(self, other) self <= other —-le__(self, other) self > other --gt__(self, other) self >= other ~.ge__(self, other) item in self _-contains__(self, item) bool (self) _-bool__(self) if self: if not self: bytes(self) ~-bytes__(self) complex(se1f) —_complex__(self) float(self) ~-float__(self) int(self) ~-int__(self) round(self) —-round__(self[, ndigits]) [Link](self) ~_ceil__(self) math. floor (self) =-floor__(self) math. trunc(self) ~-trune__(self) dir(self) _dir__(self) format (self) --format__(self, format_spec) hash(self) (self) iter (self) (self) Jen(self) ~-len__(self) repr(self) ~-repr__(self) reversed(self) _-reversed__(self) str(self) —-str__(self) self(*args, *#kwds) Trcali__(self, *args, **kwds) self[.] _-getitem__(self, key) self(.] = 1 _-setitem__(self, key, value) del self[.] —-deliten__(self, key) other[ self} _-index__(self) self name _-getattribute__(self, name) ~agetattr__(self, name) [if AttributeError] [Link] = 1 —-setattr__(self, name, value) del [Link] —delattr__(self, name) with self: _-enter__(self) —-exit__(self, exc_type, exc value, traceback) await self --await__(self) fe Decorator syntax passes a function or class to a callable and replaces it with the return value. 14 of 26 © [Link] Python 3.8+ | 2024 Jun 15 The *Best Python Cheat Sheet def show_call(obj): Decorator that prints obj name and arguments each time obj is called. def show_call_wrapper(*args, **kwds) : print(obj.—-name_, args, kwds) return obj(#args, **kwds) return show.call_wrapper @show_call # function decorator def add(x, y): return x + y # is equivalent to add = [Link](add) >o> add(13, 29) add (13, 29) {} 42 @show_call # class decorator class C def _init__(self, pass None): # is equivalent to C = show_call(C) >>> C(a=42) © () (a's 42} Python 3.8+ | 2024 Jun 15 © [Link] 15 of 26 The *Best Python Cheat Sheet # decorators optionally take arguments def show_call_if (condition) : Apply show_call decorator only if condition is True. return [Link] if condition else lambda obj: obj @show_call_if(False) def add(x, y return x + y # is equivalent to add = show_call_if(False) (add) pe add(13, 29) 42 @show.call_if(True) def add(x, y! return x ty >>> add(13, 29) add (13, 29) {} 42 pee add. __name__ show.call_wrapper’ # ugh! decorated function has different metadata # @vraps decorator copies metadata of decorated object to wrapped object # preserving original attributes (e.g. —_name_. from functools import wraps def show_call_; ‘ewraps(obj) def show_call_wrapper(*args, **kwds) : print(obj.__name__, args, kwds) return obj(*args, **kwds) return show_call_wrapper reserve_meta(obj) : @show_call_preserve_meta def add(x, y): return x+y oe add.__name__ add" An iterator implements the __iter__() method, returning an iterable that implements the _-next._() method. The _next..() method returns the next item in the collection and raises StopIteration when done. 16 of 26 © [Link] Python 3.8+ | 2024 Jun 15 The *Best Python Cheat Sheet class C: def __init__(self, items): [Link] = items def __iter__(self): “Nake class its own itereble." return self def __next__(self): "Implement to be iterable if [Link]: return [Link]() raise StopIteration >>> e = C([13, 29]) >>> it = iter(c) # get iterator >>> next(it) # get next item 29 >>> for item inc: # iterate over C instance ae print (item) 13 eos A function with a yield statement returns a generator iterator and suspends function Processing. Each iteration over the generator iterator resumes function execution, returns the next yield value, and suspends again. def gen(): "Generator function for i in [13, 29]: yield i 25> g = gen() >>> next(g) # next value 13 22> for item in gen(): # iterate over values : print(item) 13 29 >>> list(gen()) # list all values 3, 29] def parent_gen(): yield from gen() # delegate yield to another generator >>> list(parent_gen()) (13, 29] # ( for in [ if ]) >>> g = (item for item in [13, 29] if item > 20) >>> list(g) [29] Python 3.8+ | 2024 Jun 15 © [Link] 17 of 26 The *Best Python Cheat Sheet Inmutable sequence of characters. ins ‘True if string s-lower() To loner case contains substring “5 upper() Ta laper eau [Link]( True if string sterts SIaEE [, start[, end]]) with prefix, sreitled) Re eee optionally Search bounded substring [Link]() Capitalize First [Link]([, True if string ends ante: startl, end]]) with suffix, [Link](old, new[, Replace old with new optionally Search count) at most count tines bounide( eunetring [Link]() Use [Link](charseNone) Strip whitespace from [Link]() both ends, or passed to generate table characters chr () Integer to Unicode [Link](chars-None) Strip whitespace from character left end, or passed — ord() Unicode character to characters trecal [Link](chars-None) Strip whitespace fron §.isdecimal() Time 3 1651 TAT right end, or passed eat characters 5 ; 7 : True 2 ejust(wiath, Left justify ww HHOEED Tee of dedecinal() fillchar=' ') fillchar = E Tri [Link](width, Right justify with S-#enunerde() Trash tedigitl) or fillchar=" ') fillchar 5 = [Link] (width, Center with filichar S-*S#2num() ee fillehar=' ') . ae s. isprintablet True if isalaun() or [Link](sep=None, ‘Split on whitespace, i 0 [198%] 0 maxsplit=-1) or sep str at most - maxsplit times [Link]() True if [ \t\n\r\fivixte- [Link](keepends Split lines on Vx F\x65\xa.] =False) [in\r\fivixte- \xie\x88\u2028\u2629] head, sep, tail = Search for separator and \e\a [Link](.join() Strings with head, sep, tail = Search for separator separator string [Link]() Index of first match °°) one [Link]() Index of first match or raise ValueError 8-removesuffix() present ‘Sequence Escape Literal backslash WV Single quote \ Double quote ve Backspace \b Carriage return \r 18 of 26 © [Link] Python 3.8+ | 2024 Jun 15 Sequence Newline Tab Vertical tab Null Hex value Octal value Unicode 16 bit Unicode 32 bit Unicode name ara Escape curly braces Expression Justify left Justify center Justify right Justify left with char Justify right with char Trim Trim justify left ascii() repr() str() Justify left repr() Date format Significant figures Fixed-point notation Scientific notation Percentage Pad with zeros Pad with spaces Pad before sign Pad after sign Separate with commas Separate with underscores Fs}! Binary Octal Hex chr() The *Best Python Cheat Sheet Escape \n \t wv \e \xff \o77 \uxxxx Wie \N{name} f-string POY ¥"{6/3}, {'a'+'b'} {0} format(6/3, ‘a'+'b') ¥' (1:<5)" #4145)" Fa 35)" (1: <5)" F175} f"{abe" :.2} F{"abo' :6.2}" F{via} F'{vir} F'{vis} f"{‘abe! !r:6} F! {today :%d %b XY)" #1 {1.234;.2}' #7 (1.234: .2F)" #°(1.284:.2e} 11.234: 2%)" £°(1.7:04} #0734) °{123:+6}" £°(123:=+6) '{123456:,}' #1(123456:_}" #412} #'{164:b} #°{164:0}" £'{164:X} £'{164:c}" ‘ab ab ascii(v) repr(v) str(v) ‘abe "21 Jan 1984" 1.2 77.28" "1.2306+00) 123 40%" "e1.7 iat +123" + 123 123,456" 123.456" 1122" (= prepends) 10100100 "24a a vy Standard library re module provides Python regular expressions. Python 3.8+ | 2024 Jun 15 [Link] 19 of 26 The *Best Python Cheat Sheet >>> import re >>> my_re >>> match >>> [Link]() name is Douglas’ >>> [Link](1) “Douglas: >>> [Link] ()[ ‘name ] Douglas’ Any character (newline if DOTALL) * Start of string (every line if MULTILINE) 8 End of string (every line if MULTILINE) * @ or more of preceding + 1 or more of preceding 2 @ or 1 of preceding *7, +2, 22 Same as *, + and ?, as few as possible {m,n} m to n repetitions {m,n}? possible NOT character set Escape chars ‘*7+8S|()', introduce special sequences special \ Match by integer group reference starting from 1 \A Start of string \b Word boundary (see flag: ASCIT|LOCALE) \B Not word boundary (see flag ASCIT|LOCALE) \d Decimal digit (see flag: ASCII) \o Non-decimal digit (see flag ASCII) m to n repetitions, as few as Character set: e.g. ‘[a-zA-Z]" [Link](r’name is (?P[A-Za-z]+)') my_re.search('My name is Douglas.) (-) GQ: Q Pename>..) (2P=name) ) (1) (222) (1) e (group)A|B ) (?letters) (#2) \s \s Ww ww \Z Literal *\ or Group Non-capturing group Named group Match text matched by earlier group Match next, non-consumptive Non-match next, non-consumptive Match preceding, positive lookbehind assertion Non-match preceding, negative lookbehind assertion Conditional match - A if group previously matched else B Set flags for RE (‘i" Yet Oy. Teh Comment (ignored) Whitespace [ \t\n\r\fv] (see flag: ASCII) Non-whitespace (see flag: ASCII) Alphanumeric (see flag: ASCII | LOCALE) Non-alphanumeric (see flag ASCII | LOCALE) End of string Flags modify regex behaviour. Pass to regex functions (e.g. re.A | [Link]) or embed in regular expression (e.g. (?a)). 20 of 26 [Link] Python 3.8+ | 2024 Jun 15 (2a) | A | ASCIT (2i) | I | IGNORECASE (AL) | L | LOCALE ‘compile(pattern[, flags=6]) escape(string) match(pattern, string, flags]) search(pattern, string[, flags]) split (pattern, string[, maxsplit=6]) flags groupindex pattern match(string[, pos][, endpos]) search(string[, pos] [, endpos]) match Python 3.8+ | 2024 Jun 15 endpos passed to sear The *Best Python Cheat Sheet ASCII-only match for \w, AW, \b, \B, \d, \D, \s, \S (default is Unicode) Case insensitive matching Apply current locale for \w, \W, \b, \B (discouraged) Compiles Regular Expression Obj Escape non- alphanumerics Match from start Match anywhere Splits by pattern, keeping splitter if grouped Flags {group name: group number} Pattern Match from start of target [pos :endpos] Match anywhere in target [pos:endpos] pos passed to search or match hor (2m) | M | MULTILINE (?s) | S | DOTALL (2x) |X | VERBOSE DEBUG findall (pattern, string) finditer(pattern, string[, flags]) sub(pattern, repl, string[, count=@]) subn(pattern, repl, string[, count=@]) split(string[, maxsplit=@]) findall(string[, pos[, endpos}]) Finditer(stringl, pos[, endpos]]) sub(repl, string[, count=8]) subn(repl, stringl, 1) Match every new line, not only start/end of string "matches ALL chars, including newline Ignores whitespace outside character sets Display expression debug info Non-overlapping matches as list of groups or tuples (>1) Tterator over non- overlapping matches Replace count first leftmost non- overlapping; If repl is function, called with a Match0bj Like sub(), but returns (newString, nunberofSubsMade) See split() function See findall() function See finditer() function ‘See sub() function See subn() function re RE object [Link] 21 of 26 The *Best Python Cheat Sheet group({gi, One or more groups of match 92, ...1)' One arg, result is a string Multiple args, result is tuple If gi is , returns the entire matching string If 1 <= gi <= 99, returns string matching group (None if no such group) Nay also be a group name Tuple of match groups Non-participating groups are None String if len(tuple) start(group) Indices of start & end of » end(group) group match (None if group 1 string span(group) (start(group), end(group) ) (None, None) if group didn't contibute String passed to match() or search() exists but didn't contribute) bool ([object]) True, False int([float | str|bool]) 5 float ([int|str|bool]) 5.1, 1.2e-4 complex(real=8, ima 3-2), 2.1 + 0.83 [Link](, ) decimal .Decimal({str|int]) ) bin(fint]) ab101010 int('1@1610', 2) int(‘9b161918", 6) hex([int]) Ox2a int('2a", 16) int("@x2a', @) Boolean, see __bool__ special’ method Integer, see _int__ special method Float (inexact, compare with [Link](, ) See __float__ special method Complex, see __complex__ special method Fraction Decimal (exact, set precision [Link]().prec = ) Binary Hex ‘Also see built-in functions abs, pow, round, sum, min, max. from math import (e, pi, inf, nan, isinf, isnan, sin, cos, tan, asin, acos, atan, degrees, radians, log, 1og1@, 1092) from statistics import mean, median, variance, stdev, quantiles, groupby 22 of 26 © [Link] Python 3.8+ | 2024 Jun 15 The *Best Python Cheat Sheet >>> from random import random, randint, choice, shuffle, gauss, triangular, seed >>> random() # float inside [6, 1) @.42 >> randint(1, 1@) # int inside [, ] 42 >>> choice(range(10@)) # random item from sequence 42 The datetime module provides immutable hashable date, time, datetime, and timedelta classes. Output Day name short (Non) Day name full (Monday) Wonth name short (Jan) Month name full (January) Locale datetime format Day of month [61,31] oF Wicrosecond [980000, 999999] oH Hour (24-hour) [68,23] “E Hour (12-hour) [61,12] “i Day of year [861,366] am Month [61,12] om Minute [00, 59] *p Locale format for AM/PM 4s Second [80,61]. Yes, 61! su Week number (Sunday start) [@@(partial), 53] on Day number [@(Sunday), 6] ‘ Week number (Monday start) [@0(partial), 53] x. Locale date format x Locale time format wy Year without century [00,99] wy Year with century (2623) wz Time zone ("" if no TZ) wz UTC offset (+HHMM/-HHWM, °' if no TZ) 4% Literal ‘%" Python 3.8+ | 2024 Jun 15 © [Link] 23 of 26 The *Best Python Cheat Sheet try: [except [[ as e]] [except: # catch all [else: # if no exception -] [finally: # always executed raise ] try: 1/8 except ZeroDivisionError: # from None hides exception context raise TypeError("Hide ZeroDivisionError") from None 24 of 26 © [Link] Python 3.8+ | 2024 Jun 15 The *Best Python Cheat Sheet BaseException BaseExceptionGroup jeratorExit KeyboardInterrupt systenExit Exception }- ArithmeticError FloatingPointérror Overflovérror ZeroDivisionError L AssertionError L attrabuteerror [ guffererror L corerror [- ExceptionGroup }- Inportérror WoduleNotFoundError }- LookupError © Indexérror \ keyError [ Nemoryerror L naneerror © unboundLocalerror Error Blockingloérror ChildProcesstrror ConnectionError E BrokenPipeError ConnectionResetError Fileéxistserror FileNotFoundError InterruptedError TsADirectoryError NotADirectoryError PermissionError ProcessLookupError TimeoutError 1 ReferenceError f+ Runtimeerror NotImplenentedérror RecursionError }: StopAsyncIteration }- Stoprteration f- Syntaxérror © Indentationérror TabError }- Systenérror f Typetrror }- valuetrror U Unicodeerror UnicodeDecodeérror UnicodeEncoderror UnicodeTranslateError L warning BytesWarning Deprecationliarning EncodingWarning Futurevfarning Inportwarning ResourceNarning Runtinearning ‘Syntaxitarning UnicodeWarning Useritarning Base class for all exceptions Base class for groups of exceptions Generator close() raises to terminate iteration On user interrupt key (often ‘CTRL-C') On [Link]() Base class for errors Base class for arithmetic errors Floating point operation failed Result too large Argument of division or modulo is @ Assert statenent failed Attribute reference or assignnent failed Buffer operation failed input() hit end-of-file without reading dete Group of exceptions raised together Inport statement failed Wodule not able to be found Base class for lookup errors Index not found in sequence Key not found in dictionary Operation ran out of menory Local or global name not found Local variable value not assigned System related error Non-blocking operation will block Operation on child process failed Base class for connection errors Write to closed pipe or socket ConnectionAbortedError Connection aborted GonnectionRefusedError Connection denied by server Connection reset mid-operation Trying to create @ file that already exists File or directory not found System call interrupted by signal File operation requested on a directory Directory operation requested on a non-directory Operation has insuffient access rights Operation on process that no longer exists Operation timed out Weak reference used on garbage collected object Error detected thet doesn’t fit other categories Operation not yet implenented Maximum recursion depth exceeded Iterator __anext__() raises to stop iteration Iterator fext() raises when no more values Python syntax error Base class for indentation errors Inconsistent tabs or spaces Recoverable Python interpreter error Operation applied to wrong type object Operation on right type but wrong value Unicode encoding/decoding error Unicode decoding error Unicode encoding error Unicode translation error Base class for warnings Warnings about bytes and bytesarrays Warnings about deprecated features Warning about encoding problem Warnings about future deprecations for end users Possible error in module imports PendingDeprecationNarning llarnings about pending feature deprecetions Warning about resource u: Warning about dubious runtime behavior Warning about dubious syntax Warnings related to Unicode Warnings generated by user code Python 3.8+ | 2024 Jun 15 © [Link] 25 of 26 The *Best Python Cheat Sheet Execution $ python [-bBdEhil0gsSuvvWx?] [-c command | -m module-name | script | - ] [args] $ python --version Python 3.1@.12 python --help[-al1] # help-all [3.114] Execute code from command line python -c ‘print("Hello, world!")' Execute __main__.py in directory python Execute module as python -m timeit -s ‘setup here’ ‘benchmarked code here Optimise execution python -0 [Link] # Hide warnings PYTHONWARNINGS="ignore’ # OR § python -W ignore [Link] # OR import warnings warnings. filterwarnings( "ignore", category=DeprecationWlarning) # module of executed script is assigned __name__ ‘__main__’ # so to run main() only if module is executed as script if -name__ == '_main__': main() SmnRen PYTHONHOME Change location of PYTHONOPTIMIZE Optimise execution (-0) Standard Python Libraries pyTHONWARNINGS Set warning level PYTHONPATH Augnent default search [default/error/always/mod path for module files ule/once/ignore} (-W) PYTHONSTARTUP Module to execute before PYTHONPROFILEIMP Show module import tines entering interactive ORTTINE (x) prompt Sz Before __main__ module is executed Python automatically imports: m [Link] in the system site-packages directory [Link] in the user site-packages directory # Get user site packages directory $ python -m site --user-site # Bypass [Link]/[Link] hooks $ python -S [Link] 26 of 26 © [Link] Python 3.8+ | 2024 Jun 15

Você também pode gostar