python-cheatsheet README

The project's README from github.com/gto76/python-cheatsheet. As one markdown file: README.md.

Comprehensive Python Cheatsheet

Download text file, Fork me on GitHub or Check out FAQ.

Monty Python

Contents

    1. Collections:         List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator.
    2. Data Types:         Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime.
    3. Syntax Rules:      Function, Inline, Import, Decorator, Class, Duck_Type, Enum, Except.
    4. System Calls:      Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands.
    5. Data Formats:     JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque.
    6. Misc Topics:        Operator, Match_Statement, Logging, Introspection, Threads, Asyncio.
    7. Pip Packages:     Progress_Bar, Plot, Table, Console_App, GUI, Scraping, Web, Profile.
    8. Multimedia:         NumPy, Image, Animation, Audio, Synthesizer, Pygame, Pandas, Plotly.

Main

if __name__ == '__main__':      # Skips indented lines of code if file was imported.
    main()                      # Executes user-defined `def main(): ...` function.

List

<list> = [<el>, <el>, ...]      # Creates new list object. E.g. `list_a = [1, 2, 3]`.
<el>   = <list>[index]          # First index is 0, last -1. Also `<list>[i] = <el>`.
<list> = <list>[<slice>]        # Also <list>[from_inclusive : to_exclusive : ±step].
<list>.append(<el>)             # Appends element to the end. Or `<list> += [<el>]`.
<list>.extend(<coll>)           # Appends collection's items. Or `<list> += <coll>`.
<list>.sort()                   # Sorts in ascending order. Accepts `reverse=True`.
<list>.reverse()                # Reverses the order of elements. Takes linear time.
<list> = sorted(<coll>)         # Returns a new sorted list. Accepts `reverse=True`.
<iter> = reversed(<list>)       # Returns reversed iterator. Also list(<iterator>).
<el>  = max(<coll>)             # Returns the largest element. Also min(<el>, <el>).
<num> = sum(<coll>)             # Returns a sum of elements. Also math.prod(<coll>).
elementwise_sum  = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<coll>, key=lambda pair: pair[1])
sorted_by_both   = sorted(<coll>, key=lambda p: (p[1], p[0]))
flatter_list     = list(itertools.chain.from_iterable(<list>))
<int> = len(<list/dict/set/…>)  # Returns number of items. Doesn't accept iterators.
<int> = <list>.count(<el>)      # Counts occurrences. Also `if <el> in <coll>: ...`.
<int> = <list>.index(<el>)      # Returns index of first occ. or raises ValueError.
<el>  = <list>.pop()            # Removes item from the end (or at index if passed).
<list>.insert(<int>, <el>)      # Inserts item at index and shifts remaining items.
<list>.remove(<el>)             # Removes the first occurrence or raises ValueError.
<list>.clear()                  # Removes all items. Also provided by dict and set.

Dictionary

<dict> = {key: val, key: val, ...}            # Use `<dict>[key]` to get or assign the value.
<view> = <dict>.keys()                        # A collection of keys reflecting all changes.
<view> = <dict>.values()                      # A collection of values that reflects changes.
<view> = <dict>.items()                       # Coll. of tuples. Each contains key and value.
value  = <dict>.get(key, default=None)        # Returns 'default' argument if key is missing.
value  = <dict>.setdefault(key, default)      # Returns/writes 'default' when key is missing.
<dict> = collections.defaultdict(<type>)      # Dict with automatic default value `<type>()`.
<dict> = dict(<collection>)                   # Creates a dict from coll. of key-value pairs.
<dict> = dict(zip(keys, values))              # Creates key-value pairs from two collections.
<dict> = dict.fromkeys(keys [, value])        # Items get value None if only keys are passed.
<dict>.update(<dict>)                         # Adds items to dict. Passed dict has priority.
value = <dict>.pop(key)                       # Removes item or raises KeyError when missing.
{k for k, v in <dict>.items() if v == 123}    # Returns a set of keys whose value equals 123.
{k: v for k, v in <dict>.items() if k in ks}  # Returns a dict of items with specified keys.

Counter

>>> from collections import Counter
>>> counter = Counter(['blue', 'blue', 'red'])
>>> counter['yellow'] += 3
>>> print(counter.most_common())
[('yellow', 3), ('blue', 2), ('red', 1)]

Set

<set> = {<el>, <el>, ...}           # Coll. of unique items. Also set(), set(<coll>).
<set>.add(<el>)                     # Adds item to the set. Same as `<set> |= {<el>}`.
<set>.update(<coll> [, ...])        # Adds items to the set. Same as `<set> |= <set>`.
<set> = <set>.union(<coll>)         # Returns a set of all items. Also <set> | <set>.
<set> = <set>.intersection(<coll>)  # Returns every shared item. Also <set> & <set>.
<set> = <set>.difference(<coll>)    # Returns set's unique items. Also <set> - <set>.
<bool> = <set>.issuperset(<coll>)   # Returns False when collection has unique items.
<bool> = <set>.issubset(<coll>)     # Is collection a superset? Also <set> <= <set>.
<el> = <set>.pop()                  # Removes one of items. Raises KeyError if empty.
<set>.remove(<el>)                  # Removes the item or raises KeyError if missing.
<set>.discard(<el>)                 # Same as remove() but it doesn't raise an error.

Frozen Set

<frozenset> = frozenset(<collection>)

Tuple

Tuple is an immutable and hashable list.

<tuple> = ()                        # Returns an empty tuple. Also tuple(), tuple(<coll>).
<tuple> = (<el>,)                   # Returns tuple with one element. Or `<tup.> = <el>,`.
<tuple> = (<el>, <el> [, ...])      # Returns a tuple. Or `<tuple> = <el>, <el> [, ...]`.

Named Tuple

Tuple's subclass with named elements.

>>> import collections as co
>>> Point = co.namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
>>> print(p)
Point(x=1, y=2)
>>> p.x, p[1]
(1, 2)

Range

A sequence of evenly spaced integers.

<range> = range(stop)                # I.e. range(to_exclusive). Ints from 0 to `stop-1`.
<range> = range(start, stop)         # I.e. range(from, to_exc). From start to `stop-1`.
<range> = range(start, stop, step)   # I.e. range(from_inclusive, to_exclusive, ±step).
>>> [i for i in range(3)]
[0, 1, 2]

Enumerate

Iterator that zips collection with range.

for i, el in enumerate(<coll>):
    print(f'Element {el} has index {i}.')

Iterator

Potentially endless stream of elements.

import itertools as it
<iter> = iter(<coll>)                    # Iterator that returns passed elements one by one.
<iter> = iter(<func>, to_exc)            # Calls `<func>()` until it receives 'to_exc' value.
<iter> = (<expr> for <name> in <coll>)   # E.g. `(i+1 for i in range(3))`. Evaluates lazily.
<el>   = next(<iter> [, default])        # Raises StopIteration or returns 'default' on end.
<list> = list(<iter>)                    # Returns a list of iterator's remaining elements.
<iter> = it.count(start=0, step=1)       # Returns updated 'start' endlessly. Accepts floats.
<iter> = it.repeat(<obj> [, times])      # Returns passed element endlessly or 'times' times.
<iter> = it.cycle(<coll>)                # Repeats the sequence endlessly. Accepts iterators.
<iter> = it.chain(<coll>, <coll>, ...)   # Returns each element of each collection in order.
<iter> = it.chain.from_iterable(<coll>)  # Accepts collection (i.e. iterable) of collections.
<iter> = it.islice(<coll>, stop)         # Also accepts 'start' and 'step'. Args can be None.
<iter> = it.product(<coll>, <coll>)      # Same as `((a, b) for a in arg_1 for b in arg_2)`.

Generator

def count(start, step):
    while True:
        yield start
        start += step
>>> counter = count(10, 2)
>>> next(counter), next(counter), next(counter)
(10, 12, 14)

Type

<type> = type(<obj>)                   # Object's type. Also `<obj>.__class__`.
<bool> = isinstance(<obj>, <type>)     # Also `issubclass(type(<obj>), <type>)`.
>>> type('a'), 'a'.__class__, str
(<class 'str'>, <class 'str'>, <class 'str'>)

Some types do not have built-in names, so they must be imported:

from types import FunctionType, MethodType, LambdaType, GeneratorType

Abstract Base Classes

Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. An ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods that class has implemented. For instance, Iterable ABC looks for method iter(), while Collection ABC looks for iter(), contains() and len().

>>> from collections.abc import Iterable, Collection, Sequence
>>> isinstance([1, 2, 3], Iterable)
True
+------------------+------------+------------+------------+
|                  |  Iterable  | Collection |  Sequence  |
+------------------+------------+------------+------------+
| list, range, str |    yes     |    yes     |    yes     |
| dict, set        |    yes     |    yes     |            |
| iter             |    yes     |            |            |
+------------------+------------+------------+------------+
>>> from numbers import Number, Complex, Real, Rational, Integral
>>> isinstance(123, Number)
True
+--------------------+---------+---------+--------+----------+----------+
|                    |  Number | Complex |  Real  | Rational | Integral |
+--------------------+---------+---------+--------+----------+----------+
| int                |   yes   |   yes   |  yes   |   yes    |   yes    |
| fractions.Fraction |   yes   |   yes   |  yes   |   yes    |          |
| float              |   yes   |   yes   |  yes   |          |          |
| complex            |   yes   |   yes   |        |          |          |
| decimal.Decimal    |   yes   |         |        |          |          |
+--------------------+---------+---------+--------+----------+----------+

String

Immutable sequence of characters.

<str>  = 'abc'                       # Also "abc". Interprets \n, \t, \x00-\xff, etc.
<str>  = <str>.strip()               # Strips all whitespace characters from both ends.
<str>  = <str>.strip('<chars>')      # Strips passed characters. Also lstrip/rstrip().
<list> = <str>.split()               # Splits it on one or more whitespace characters.
<list> = <str>.split(<str>)          # Splits on passed string. Also `maxsplit=<int>`.
<list> = <str>.splitlines()          # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
<str>  = <str>.join(<coll_of_str>)   # Joins items by using the string as a separator.
<bool> = <str> in <str>              # Returns True if string contains the substring.
<bool> = <str>.startswith(<str>)     # Pass tuple of strings to give multiple options.
<int>  = <str>.find(<str>)           # Returns start index of the first match or `-1`.
<str>  = <str>.lower()               # Lowers the case. Also upper/capitalize/title().
<str>  = <str>.casefold()            # Lower() that converts ẞ/ß to ss, Σ/ς to σ, etc.
<str>  = <str>.replace(old, new)     # Removes occurrences of string old if new is ''.
<str>  = <str>.translate(table)      # Get table via str.maketrans(<chr_to_str_dict>).
<str>  = chr(<int>)                  # Converts passed integer into Unicode character.
<int>  = ord(<str>)                  # Converts passed Unicode character into integer.
<bool> = <str>.isdecimal()           # Checks all chars for [0-9]. Also [०-९], [٠-٩].
<bool> = <str>.isdigit()             # Checks for [²³¹…] and isdecimal(). Also [፩-፱].
<bool> = <str>.isnumeric()           # Checks for [¼½¾…] and isdigit(). Also [零〇一…].
<bool> = <str>.isalnum()             # Checks for [ABC…] and isnumeric(). Also [ªµº…].
<bool> = <str>.isprintable()         # Checks for [ !"#…], basic emojis and isalnum().
<bool> = <str>.isspace()             # Checks for [ \t\n\r\f\v\x1c\x1d\x1e\x1f\x85…].

Regex

Functions for regular expression matching.

import re
<str>   = re.sub(r'<regex>', new, text)  # Substitutes occurrences with string 'new'.
<list>  = re.findall(r'<regex>', text)   # Returns all occurrences as string objects.
<list>  = re.split(r'<regex>', text)     # Add brackets around regex to keep matches.
<Match> = re.search(r'<regex>', text)    # Returns first occ. of the pattern or None.
<Match> = re.match(r'<regex>', text)     # Only searches at the start of the 'text'.
<iter>  = re.finditer(r'<regex>', text)  # Returns all occurrences as Match objects.

Match Object

<str>   = <Match>.group()                # Returns the whole match. Also group(0).
<str>   = <Match>.group(1)               # Returns part inside the first brackets.
<tuple> = <Match>.groups()               # Returns all bracketed parts as strings.
<int>   = <Match>.start()                # Returns start index of the whole match.
<int>   = <Match>.end()                  # Returns the match's end index plus one.

Special Sequences

'\d' == '[0-9]'                          # Also [०-९…]. Matches decimal character.
'\w' == '[a-zA-Z0-9_]'                   # Also [ª²³…]. Matches alphanumeric or _.
'\s' == '[ \t\n\r\f\v]'                  # Also [\x1c-\x1f…]. Matches whitespace.

Format

String formatting mechanisms.

<str> = f'{<obj>}, {<obj>}'             # Braces can also contain expressions.
<str> = '{}, {}'.format(<obj>, <obj>)   # Or '{0}, {a}'.format(<obj>, a=<obj>).
<str> = '%s, %s' % (<obj>, <obj>)       # Old and redundant formatting method.

Example

>>> Person = collections.namedtuple('Person', 'name height')
>>> jean = Person('Jean-Luc', 187)
>>> f'{jean.name} is {jean.height / 100} meters tall.'
'Jean-Luc is 1.87 meters tall.'

Options

{<obj>:<10}                             # '<obj>     '.
{<obj>:^10}                             # '  <obj>   '.
{<obj>:>10}                             # '     <obj>'.
{<obj>:.<10}                            # '<obj>.....'.
{<obj>:0}                               # '<obj>'.

Strings

{'abcde':10}                            # 'abcde     '.
{'abcde':10.3}                          # 'abc       '.
{'abcde':.3}                            # 'abc'.
{'abcde'!r:10}                          # "'abcde'   ".

Numbers

{123456:10}                             # '    123456'.
{123456:10,}                            # '   123,456'.
{123456:10_}                

python-cheatsheet (gto76/python-cheatsheet)

Searching Database…

这是什么?一份全面的参考速查表,涵盖 Python 语法、内置类型、标准库模块和常用的 pip 包,按集合、数据类型、语法规则、系统调用、数据格式和多媒体等主题组织。
这是教程,还是我可以用来查找内容的参考资料?它是参考速查表,而不是分步教程:按主题分组,提供简短的代码片段和说明,便于快速查找语法和标准库的用法。
内容是如何组织的?我该从哪里开始?内容分为八个编号章节(集合、数据类型、语法规则、系统调用、数据格式、杂项主题、pip 包、多媒体),每个章节又划分为若干子主题,您可以直接跳到所需主题,例如 List、Regex 或 JSON。
使用这份资料前需要安装什么吗?不需要,它是供阅读的纯文本/Markdown 内容;只有在介绍特定主题时,部分示例才会用到 NumPy、Pandas 或 Plotly 等第三方 pip 包。
它是否与最新的 Python 版本保持同步?它会跟进 Python 的最新变化,例如指出从 Python 3.12 开始,原始字符串中的正则表达式转义序列会引发 SyntaxWarning。
没有网络时我也能使用吗?可以,它提供可下载的文本文件版本,因此您可以完全离线阅读。
它涵盖第三方库,还是只讲 Python 核心内容?两者都有:大多数章节讲解 Python 核心内容(集合、数据类型、语法、系统调用),同时还有专门的章节介绍常用的 pip 包和多媒体库,例如 NumPy、Pandas、Pygame 和 Plotly。
它会解释正则表达式的标志和特殊序列吗?会,它记录了 IGNORECASE、MULTILINE、DOTALL 等正则函数参数,并说明 ASCII 标志如何改变 \s、\d、\w 等特殊序列的匹配方式。
Creator
gto76
Size
13.5 MB
Stars
38.7K
Age
8y
Commits · 90 Days