Main
if name == 'main': # Runs main() if file wasn't imported.
main()
List
= [] # Or: [from_inclusive : to_exclusive : ±step]
.append() # Or: += []
.extend() # Or: += .sort() # Sorts in ascending order.
.reverse() # Reverses the list in-place.
= sorted() # Returns a new sorted list.
= reversed() # Returns reversed iterator.
sum_of_elements = sum()
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(, key=lambda el: el[1])
sorted_by_both = sorted(, key=lambda el: (el[1], el[0]))
flatter_list = list(itertools.chain.from_iterable())
product_of_elems = functools.reduce(lambda out, el: out * el, )
list_of_chars = list()
For details about sorted(), min() and max() see sortable.
Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.
.insert(, ) # Inserts item at index and moves the rest to the right.
= .pop([]) # Removes and returns item at index or from the end.
= .count() # Returns number of occurrences. Also works on strings.
= .index() # Returns index of the first occurrence or raises ValueError.
.remove() # Removes first occurrence of the item or raises ValueError.
.clear() # Removes all items. Also works on dictionary and set.
Dictionary
= .keys() # Coll. of keys that reflects changes.
= .values() # Coll. of values that reflects changes.
= .items() # Coll. of key-value tuples that reflects chgs.
value = .get(key, default=None) # Returns default if key is missing.
value = .setdefault(key, default=None) # Returns and writes default if key is missing.
= collections.defaultdict() # Returns a dict with default value of type.
= collections.defaultdict(lambda: 1) # Returns a dict with default value 1.
= dict() # Creates a dict from coll. of key-value pairs.
= dict(zip(keys, values)) # Creates a dict from two collections.
= dict.fromkeys(keys [, value]) # Creates a dict from collection of keys.
.update() # Adds items. Replaces ones with matching keys.
value = .pop(key) # Removes item or raises KeyError.
{k for k, v in .items() if v == value} # Returns set of keys that point to the value.
{k: v for k, v in .items() if k in keys} # Returns a dictionary, filtered by keys.
Counter
>>> from collections import Counter
>>> colors = ['blue', 'blue', 'blue', 'red', 'red']
>>> counter = Counter(colors)
>>> counter['yellow'] += 1
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0]
('blue', 3)
Set
= set() # `{}` returns a dictionary.
.add() # Or: |= {}
.update( [, ...]) # Or: |= = .union() # Or: | = .intersection() # Or: & = .difference() # Or: - = .symmetric_difference() # Or: ^ = .issubset() # Or: <= = .issuperset() # Or: >= = .pop() # Raises KeyError if empty.
.remove() # Raises KeyError if missing.
.discard() # Doesn't raise an error.
Frozen Set
Is immutable and hashable.
That means it can be used as a key in a dictionary or as an element in a set.
= frozenset()
Tuple
Tuple is an immutable and hashable list.
= () # Empty tuple.
= (,) # Or: ,
= (, [, ...]) # Or: , [, ...]
Named Tuple
Tuple's subclass with named elements.
>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
Range
Immutable and hashable sequence of integers.
= range(stop) # range(to_exclusive)
= range(start, stop) # range(from_inclusive, to_exclusive)
= range(start, stop, ±step) # range(from_inclusive, to_exclusive, ±step_size)
>>> [i for i in range(3)]
[0, 1, 2]
Enumerate
for i, el in enumerate( [, i_start]):
...
Iterator
= iter() # `iter()` returns unmodified iterator.
= iter(, to_exclusive) # A sequence of return values until 'to_exclusive'.
= next( [, default]) # Raises StopIteration or returns 'default' on end.
= list() # Returns a list of iterator's remaining elements.
Itertools
from itertools import count, repeat, cycle, chain, islice
= count(start=0, step=1) # Returns updated value endlessly. Accepts floats.
= repeat( [, times]) # Returns element endlessly or 'times' times.
= cycle() # Repeats the sequence endlessly.
= chain(, [, ...]) # Empties collections in order (figuratively).
= chain.from_iterable() # Empties collections inside a collection in order.
= islice(, to_exclusive) # Only returns first 'to_exclusive' elements.
= islice(, from_inclusive, …) # `to_exclusive, +step_size`. Indices can be None.
Generator
Any function that contains a yield statement returns a generator.
Generators and iterators are interchangeable.
def count(start, step):
while True:
yield start
start += step
>>> counter = count(10, 2)
>>> next(counter), next(counter), next(counter)
(10, 12, 14)
Type
Everything is an object.
Every object has a type.
Type and class are synonymous.
= type() # Or: .__class__
= isinstance(, ) # Or: issubclass(type(), )
>>> type('a'), 'a'.__class__, str
(, , )
Some types do not have built-in names, so they must be imported:
from types import FunctionType, MethodType, LambdaType, GeneratorType, ModuleType
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. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the 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
= .strip() # Strips all whitespace characters from both ends.
= .strip('') # Strips all passed characters from both ends.
= .split() # Splits on one or more whitespace characters.
= .split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
= .splitlines(keepends=False) # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
= .join() # Joins elements using string as a separator.
= in # Checks if string contains a substring.
= .startswith() # Pass tuple of strings for multiple options.
= .endswith() # Pass tuple of strings for multiple options.
= .find() # Returns start index of the first match or -1.
= .index() # Same, but raises ValueError if missing.
= .replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
= .translate(
) # Use `str.maketrans()` to generate table.
= chr() # Converts int to Unicode character.
= ord() # Converts Unicode character to int.
Also: 'lstrip()', 'rstrip()' and 'rsplit()'.
Also: 'lower()', 'upper()', 'capitalize()' and 'title()'.
Property Methods
+---------------+----------+----------+----------+----------+----------+
| | [ !#$%…] | [a-zA-Z] | [¼½¾] | [²³¹] | [0-9] |
+---------------+----------+----------+----------+----------+----------+
| isprintable() | yes | yes | yes | yes | yes |
| isalnum() | | yes | yes | yes | yes |
| isnumeric() | | | yes | yes | yes |
| isdigit() | | | | yes | yes |
| isdecimal() | | | | | yes |
+---------------+----------+----------+----------+----------+----------+
Also: 'isspace()' checks for '[ \t\n\r\f\v\x1c-\x1f\x85\u2000…]'.
Regex
import re
= re.sub(, new, text, count=0) # Substitutes all occurrences with 'new'.
= re.findall(, text) # Returns all occurrences as strings.
= re.split(, text, maxsplit=0) # Use brackets in regex to include the matches.
= re.search(, text) # Searches for first occurrence of the pattern.
= re.match(, text) # Searches only at the beginning of the text.
= re.finditer(, text) # Returns all occurrences as Match objects.
Argument 'new' can be a function that accepts a Match object and returns a string.
Search() and match() return None if they can't find a match.
Argument 'flags=re.IGNORECASE' can be used with all functions.
Argument 'flags=re.MULTILINE' makes '^' and '$' match the start/end of each line.
Argument 'flags=re.DOTALL' makes dot also accept the '\n'.
Use r'\1' or '\\1' for backreference ('\1' returns a character with octal code 1).
Add '?' after '*' and '+' to make them non-greedy.
Match Object
= .group() # Returns the whole match. Also group(0).
= .group(1) # Returns part in the first bracket.
= .groups() # Returns all bracketed parts.
= .start() # Returns start index of the match.
= .end() # Returns exclusive end index of the match.
Special Sequences
'\d' == '[0-9]' # Matches decimal characters.
'\w' == '[a-zA-Z0-9_]' # Matches alphanumerics and underscore.
'\s' == '[ \t\n\r\f\v]' # Matches whitespaces.
By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
As shown above, it restricts all special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]' (the so-called separator characters).
Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).
Format
= f'{}, {}' # Curly brackets can also contain expressions.
= '{}, {}'.format(, ) # Or: '{0}, {a}'.format(, a=)
= '%s, %s' % (, ) # Redundant and inferior C style formatting.
Attributes
>>> Person = collections.namedtuple('Person', 'name height')
>>> person = Person('Jean-Luc', 187)
>>> f'{person.height}'
'187'
>>> '{p.height}'.format(p=person)
'187'
General Options
{:<10} # ' '
{:^10} # ' '
{:>10} # ' '
{:.<10} # '......'
{:0} # ''
Options can be generated dynamically: f'{:{}[…]}'.
Adding '!r' before the colon converts object to string by calling its repr() method.
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_} # ' 123_456'
{123456:+10} # ' +123456'
{123456:=+10} # '+ 123456'
{123456: } # ' 123456'
{-123456: } # '-123456'
Floats
{1.23456:10.3} # ' 1.23'
{1.23456:10.3f} # ' 1.235'
{1.23456:10.3e} # ' 1.235e+00'
{1.23456:10.3%} # ' 123.456%'
Comparison of presentation types:
+--------------+----------------+----------------+----------------+----------------+
| | {} | {:f} | {:e} | {:%} |
+--------------+----------------+----------------+----------------+----------------+
| 0.000056789 | '5.6789e-05' | '0.000057' | '5.678900e-05' | '0.005679%' |
| 0.00056789 | '0.00056789' | '0.000568' | '5.678900e-04' | '0.056789%' |
| 0.0056789 | '0.0056789' | '0.005679' | '5.678900e-03' | '0.567890%' |
| 0.056789 | '0.056789' | '0.056789' | '5.678900e-02' | '5.678900%' |
| 0.56789 | '0.56789' | '0.567890' | '5.678900e-01' | '56.789000%' |
| 5.6789 | '5.6789' | '5.678900' | '5.678900e+00' | '567.890000%' |
| 56.789 | '56.789' | '56.789000' | '5.678900e+01' | '5678.900000%' |
+--------------+----------------+----------------+----------------+----------------+
+--------------+----------------+----------------+----------------+----------------+
| | {:.2} | {:.2f} | {:.2e} | {:.2%} |
+--------------+----------------+----------------+----------------+----------------+
| 0.000056789 | '5.7e-05' | '0.00' | '5.68e-05' | '0.01%' |
| 0.00056789 | '0.00057' | '0.00' | '5.68e-04' | '0.06%' |
| 0.0056789 | '0.0057' | '0.01' | '5.68e-03' | '0.57%' |
| 0.056789 | '0.057' | '0.06' | '5.68e-02' | '5.68%' |
| 0.56789 | '0.57' | '0.57' | '5.68e-01' | '56.79%' |
| 5.6789 | '5.7' | '5.68' | '5.68e+00' | '567.89%' |
| 56.789 | '5.7e+01' | '56.79' | '5.68e+01' | '5678.90%' |
+--------------+----------------+----------------+----------------+----------------+
When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
This rule only effects numbers that can be represented exactly by a float (.5, .25, …).
Ints
{90:c} # 'Z'
{90:b} # '1011010'
{90:X} # '5A'
Numbers
= int() # Or: math.floor()
= float() # Or: e± = complex(real=0, imag=0) # Or:
Main if name == 'main': # Runs main() if file wasn't imported. main() List
=
[] # Or:
[from_inclusive : to_exclusive : ±step]
.append() # Or:
+= []
.extend() # Or:
+=
.sort() # Sorts in ascending order.
.reverse() # Reverses the list in-place.
= sorted() # Returns a new sorted list.
= reversed(
) # Returns reversed iterator. sum_of_elements = sum()
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(, key=lambda el: el[1])
sorted_by_both = sorted(, key=lambda el: (el[1], el[0]))
flatter_list = list(itertools.chain.from_iterable(
)) product_of_elems = functools.reduce(lambda out, el: out * el,)
list_of_chars = list()
For details about sorted(), min() and max() see sortable.
Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.
.insert(, ) # Inserts item at index and moves the rest to the right.
=
.pop([]) # Removes and returns item at index or from the end.
=
.count() # Returns number of occurrences. Also works on strings.
=
.index() # Returns index of the first occurrence or raises ValueError.
.remove() # Removes first occurrence of the item or raises ValueError.
.clear() # Removes all items. Also works on dictionary and set. Dictionary = .keys() # Coll. of keys that reflects changes.
= .values() # Coll. of values that reflects changes.
= .items() # Coll. of key-value tuples that reflects chgs.
value = .get(key, default=None) # Returns default if key is missing.
value = .setdefault(key, default=None) # Returns and writes default if key is missing.
= collections.defaultdict() # Returns a dict with default value of type.
= collections.defaultdict(lambda: 1) # Returns a dict with default value 1.
= dict() # Creates a dict from coll. of key-value pairs.
= dict(zip(keys, values)) # Creates a dict from two collections.
= dict.fromkeys(keys [, value]) # Creates a dict from collection of keys.
.update() # Adds items. Replaces ones with matching keys.
value = .pop(key) # Removes item or raises KeyError.
{k for k, v in .items() if v == value} # Returns set of keys that point to the value.
{k: v for k, v in .items() if k in keys} # Returns a dictionary, filtered by keys.
Counter
>>> from collections import Counter
>>> colors = ['blue', 'blue', 'blue', 'red', 'red']
>>> counter = Counter(colors)
>>> counter['yellow'] += 1
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0]
('blue', 3)
Set
= set() # `{}` returns a dictionary.
.add() # Or: |= {}
.update( [, ...]) # Or: |=
= .union() # Or: |
= .intersection() # Or: &
= .difference() # Or: -
= .symmetric_difference() # Or: ^
= .issubset() # Or: <=
= .issuperset() # Or: >=
= .pop() # Raises KeyError if empty.
.remove() # Raises KeyError if missing.
.discard() # Doesn't raise an error.
Frozen Set
Is immutable and hashable.
That means it can be used as a key in a dictionary or as an element in a set.
= frozenset()
Tuple
Tuple is an immutable and hashable list.
= () # Empty tuple.
= (,) # Or: ,
= (, [, ...]) # Or: , [, ...]
Named Tuple
Tuple's subclass with named elements.
>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
Range
Immutable and hashable sequence of integers.
= range(stop) # range(to_exclusive)
= range(start, stop) # range(from_inclusive, to_exclusive)
= range(start, stop, ±step) # range(from_inclusive, to_exclusive, ±step_size)
>>> [i for i in range(3)]
[0, 1, 2]
Enumerate
for i, el in enumerate( [, i_start]):
...
Iterator
= iter() # `iter()` returns unmodified iterator.
= iter(, to_exclusive) # A sequence of return values until 'to_exclusive'.
= next( [, default]) # Raises StopIteration or returns 'default' on end.
= list() # Returns a list of iterator's remaining elements.
Itertools
from itertools import count, repeat, cycle, chain, islice
= count(start=0, step=1) # Returns updated value endlessly. Accepts floats.
= repeat( [, times]) # Returns element endlessly or 'times' times.
= cycle() # Repeats the sequence endlessly.
= chain(, [, ...]) # Empties collections in order (figuratively).
= chain.from_iterable() # Empties collections inside a collection in order.
= islice(, to_exclusive) # Only returns first 'to_exclusive' elements.
= islice(, from_inclusive, …) # `to_exclusive, +step_size`. Indices can be None.
Generator
Any function that contains a yield statement returns a generator.
Generators and iterators are interchangeable.
def count(start, step):
while True:
yield start
start += step
>>> counter = count(10, 2)
>>> next(counter), next(counter), next(counter)
(10, 12, 14)
Type
Everything is an object.
Every object has a type.
Type and class are synonymous.
= type() # Or: .__class__
= isinstance(, ) # Or: issubclass(type(), )
>>> type('a'), 'a'.__class__, str
(, , )
Some types do not have built-in names, so they must be imported:
from types import FunctionType, MethodType, LambdaType, GeneratorType, ModuleType
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. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the 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
= .strip() # Strips all whitespace characters from both ends.
= .strip('') # Strips all passed characters from both ends.
=.split() # Splits on one or more whitespace characters.
=.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
=.splitlines(keepends=False) # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
= .join() # Joins elements using string as a separator.
= in # Checks if string contains a substring.
= .startswith() # Pass tuple of strings for multiple options.
= .endswith() # Pass tuple of strings for multiple options.
= .find() # Returns start index of the first match or -1.
= .index() # Same, but raises ValueError if missing.
= .replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
= .translate() # Use `str.maketrans()` to generate table.
= chr() # Converts int to Unicode character.
= ord() # Converts Unicode character to int.
Also: 'lstrip()', 'rstrip()' and 'rsplit()'.
Also: 'lower()', 'upper()', 'capitalize()' and 'title()'.
Property Methods
+---------------+----------+----------+----------+----------+----------+
| | [ !#$%…] | [a-zA-Z] | [¼½¾] | [²³¹] | [0-9] |
+---------------+----------+----------+----------+----------+----------+
| isprintable() | yes | yes | yes | yes | yes |
| isalnum() | | yes | yes | yes | yes |
| isnumeric() | | | yes | yes | yes |
| isdigit() | | | | yes | yes |
| isdecimal() | | | | | yes |
+---------------+----------+----------+----------+----------+----------+
Also: 'isspace()' checks for '[ \t\n\r\f\v\x1c-\x1f\x85\u2000…]'.
Regex
import re
= re.sub(, new, text, count=0) # Substitutes all occurrences with 'new'.
= re.findall(, text) # Returns all occurrences as strings.
= re.split(, text, maxsplit=0) # Use brackets in regex to include the matches.
= re.search(, text) # Searches for first occurrence of the pattern.
= re.match(, text) # Searches only at the beginning of the text.
= re.finditer(, text) # Returns all occurrences as Match objects.
Argument 'new' can be a function that accepts a Match object and returns a string.
Search() and match() return None if they can't find a match.
Argument 'flags=re.IGNORECASE' can be used with all functions.
Argument 'flags=re.MULTILINE' makes '^' and '$' match the start/end of each line.
Argument 'flags=re.DOTALL' makes dot also accept the '\n'.
Use r'\1' or '\\1' for backreference ('\1' returns a character with octal code 1).
Add '?' after '*' and '+' to make them non-greedy.
Match Object
= .group() # Returns the whole match. Also group(0).
= .group(1) # Returns part in the first bracket.
= .groups() # Returns all bracketed parts.
= .start() # Returns start index of the match.
= .end() # Returns exclusive end index of the match.
Special Sequences
'\d' == '[0-9]' # Matches decimal characters.
'\w' == '[a-zA-Z0-9_]' # Matches alphanumerics and underscore.
'\s' == '[ \t\n\r\f\v]' # Matches whitespaces.
By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
As shown above, it restricts all special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]' (the so-called separator characters).
Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).
Format
= f'{}, {}' # Curly brackets can also contain expressions.
= '{}, {}'.format(, ) # Or: '{0}, {a}'.format(, a=)
= '%s, %s' % (, ) # Redundant and inferior C style formatting.
Attributes
>>> Person = collections.namedtuple('Person', 'name height')
>>> person = Person('Jean-Luc', 187)
>>> f'{person.height}'
'187'
>>> '{p.height}'.format(p=person)
'187'
General Options
{:<10} # ' '
{:^10} # ' '
{:>10} # ' '
{:.<10} # '......'
{:0} # ''
Options can be generated dynamically: f'{:{}[…]}'.
Adding '!r' before the colon converts object to string by calling its repr() method.
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_} # ' 123_456'
{123456:+10} # ' +123456'
{123456:=+10} # '+ 123456'
{123456: } # ' 123456'
{-123456: } # '-123456'
Floats
{1.23456:10.3} # ' 1.23'
{1.23456:10.3f} # ' 1.235'
{1.23456:10.3e} # ' 1.235e+00'
{1.23456:10.3%} # ' 123.456%'
Comparison of presentation types:
+--------------+----------------+----------------+----------------+----------------+
| | {} | {:f} | {:e} | {:%} |
+--------------+----------------+----------------+----------------+----------------+
| 0.000056789 | '5.6789e-05' | '0.000057' | '5.678900e-05' | '0.005679%' |
| 0.00056789 | '0.00056789' | '0.000568' | '5.678900e-04' | '0.056789%' |
| 0.0056789 | '0.0056789' | '0.005679' | '5.678900e-03' | '0.567890%' |
| 0.056789 | '0.056789' | '0.056789' | '5.678900e-02' | '5.678900%' |
| 0.56789 | '0.56789' | '0.567890' | '5.678900e-01' | '56.789000%' |
| 5.6789 | '5.6789' | '5.678900' | '5.678900e+00' | '567.890000%' |
| 56.789 | '56.789' | '56.789000' | '5.678900e+01' | '5678.900000%' |
+--------------+----------------+----------------+----------------+----------------+
+--------------+----------------+----------------+----------------+----------------+
| | {:.2} | {:.2f} | {:.2e} | {:.2%} |
+--------------+----------------+----------------+----------------+----------------+
| 0.000056789 | '5.7e-05' | '0.00' | '5.68e-05' | '0.01%' |
| 0.00056789 | '0.00057' | '0.00' | '5.68e-04' | '0.06%' |
| 0.0056789 | '0.0057' | '0.01' | '5.68e-03' | '0.57%' |
| 0.056789 | '0.057' | '0.06' | '5.68e-02' | '5.68%' |
| 0.56789 | '0.57' | '0.57' | '5.68e-01' | '56.79%' |
| 5.6789 | '5.7' | '5.68' | '5.68e+00' | '567.89%' |
| 56.789 | '5.7e+01' | '56.79' | '5.68e+01' | '5678.90%' |
+--------------+----------------+----------------+----------------+----------------+
When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
This rule only effects numbers that can be represented exactly by a float (.5, .25, …).
Ints
{90:c} # 'Z'
{90:b} # '1011010'
{90:X} # '5A'
Numbers
= int() # Or: math.floor()
= float() # Or: e±
= complex(real=0, imag=0) # Or: