4.

None

; (repr() str() ) print()

4.1.

if while

__bool__() False __len__() 0 [1] :

  • : None False
  • : 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • : '', (), [], {}, set(), range(0)

0 False 1 True (: or and )

4.2. and, or, not

:

x or y x y, x (1)
x and y x x, y (2)
not x x True, False (3)

:

  1. not not a == b not (a == b) a == not b

4.3.

Python 8 (); x < y <= z x < y and y <= z y ( x < y z )

:

<
<=
>
>=
==
!=
is
is not

() 2 < <= > >= TypeError

__eq__()

__lt__() __le__() __gt__() __ge__() ( __lt__() __eq__() )

is is not 2

() 2 in not in

4.4. int, float, complex

3 : C double ; sys.float_info z z.real z.imag ( fractions decimal )

() 'j' 'J' ()

Python : "" [2] int() float() complex()

() ():

x + y x y    
x - y x y    
x * y x y    
x / y x y    
x // y x y (1)  
x % y x / y (2)  
-x x    
+x x    
abs(x) x   abs()
int(x) x (3)(6) int()
float(x) x (4)(6) float()
complex(re, im) re, im im (6) complex()
c.conjugate() c    
divmod(x, y) (x // y, x % y) (2) divmod()
pow(x, y) x y (5) pow()
x ** y x y (5)  

:

  1. : 1//2 0 (-1)//2 -1 1//(-2) -1 (-1)//(-2) 0

  2. abs()

  3. C; math.floor() math.ceil()

  4. "nan" "inf" "+" "-" (Not a Number (NaN))

  5. Python pow(0, 0) 0 ** 0 1

  6. 0 9 Unicode (Nd )

    Nd http://www.unicode.org/Public/9.0.0/ucd/extracted/DerivedNumericType.txt

numbers.Real (int float) :

math.trunc(x) x Integral ()
round(x[, n]) x n n 0
math.floor(x) x Integral ()
math.ceil(x) x Integral ()

math cmath

4.4.1.

Bitwise operations only make sense for integers. Negative numbers are treated as their 2s complement value (this assumes that there are enough bits so that no overflow occurs during the operation).

; ~ (+ -)

:

x | y x y  
x ^ y x y  
x & y x y  
x << n x n (1)(2)
x >> n x n (1)(3)
~x x  

:

  1. ValueError
  2. n pow(2, n)
  3. n pow(2, n)

4.4.2.

numbers.Integral (abstract base class) :

int.bit_length()

0 :

>>> n = -37
>>> bin(n)
'-0b100101'
>>> n.bit_length()
6

x 0 x.bit_length() 2**(k-1) <= abs(x) < 2**k k abs(x) k = 1 + int(log(abs(x), 2)) x 0 x.bit_length() 0

:

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6

3.1 .

int.to_bytes(length, byteorder, *, signed=False)

>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03'

length OverflowError

byteorder byteorder "big" byteorder "little" sys.byteorder

signed 2 signed False OverflowError signed False

3.2 .

classmethod int.from_bytes(bytes, byteorder, *, signed=False)

>>> int.from_bytes(b'\x00\x10', byteorder='big')
16
>>> int.from_bytes(b'\x00\x10', byteorder='little')
4096
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes([255, 0, 0], byteorder='big')
16711680

bytes bytes-like object bytes iterable

byteorder byteorder "big" byteorder "little" sys.byteorder

signed 2

3.2 .

4.4.3.

numbers.Real (abstract base class)

float.as_integer_ratio()

OverflowError (NaN) ValueError

float.is_integer()

True False :

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False

16 16 Python 2 10 10 16 (numerical work)

float.hex()

16 0x p

classmethod float.fromhex(s)

16 s s

float.fromhex() float.hex()

16 :

[sign] ['0x'] integer ['.' fraction] ['p' exponent]

sign + - integer fraction 16 exponent 10 1 16 C99 6.4.4.2 Java 1.5 float.hex() C Java 16 C %a Java Double.toHexString float.fromhex()

16 10 2 16 0x3.a7p10 (3 + 10./16 + 7./16**2) * 2.0**10 3740.0 :

>>> float.fromhex('0x3.a7p10')
3740.0

3740.0 16 :

>>> float.hex(3740.0)
'0x1.d380000000000p+11'

4.4.4.

x y x == y hash(x) == hash(y) ( __hash__() ) (int float decimal.Decimal fractions.Fraction ) Python int fractions.Fraction float decimal.Decimal P P P sys.hash_info modulus Python

CPython : 32 bit C long P = 2**31 - 1 64-bit C long P = 2**61 - 1

:

  • x = m / n n P invmod(n, P) n P () hash(x) m * invmod(n, P) % P
  • x = m / n n P ( m ) n P hash(x) sys.hash_info.inf
  • x = m / n hash(x) -hash(-x) -1 -2
  • sys.hash_info.inf -sys.hash_info.inf sys.hash_info.nan nan () ( nan )
  • (complex) z hash(z.real) + sys.hash_info.imag * hash(z.imag) 2**sys.hash_info.width range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1)) -1 -2

float complex Python :

import sys, math

def hash_fraction(m, n):
    """Compute the hash of a rational number m / n.

    Assumes m and n are integers, with n positive.
    Equivalent to hash(fractions.Fraction(m, n)).

    """
    P = sys.hash_info.modulus
    # Remove common factors of P.  (Unnecessary if m and n already coprime.)
    while m % P == n % P == 0:
        m, n = m // P, n // P

    if n % P == 0:
        hash_value = sys.hash_info.inf
    else:
        # Fermat's Little Theorem: pow(n, P-1, P) is 1, so
        # pow(n, P-2, P) gives the inverse of n modulo P.
        hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
    if m < 0:
        hash_value = -hash_value
    if hash_value == -1:
        hash_value = -2
    return hash_value

def hash_float(x):
    """Compute the hash of a float x."""

    if math.isnan(x):
        return sys.hash_info.nan
    elif math.isinf(x):
        return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
    else:
        return hash_fraction(*x.as_integer_ratio())

def hash_complex(z):
    """Compute the hash of a complex number z."""

    hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
    # do a signed reduction modulo 2**sys.hash_info.width
    M = 2**(sys.hash_info.width - 1)
    hash_value = (hash_value & (M - 1)) - (hash_value & M)
    if hash_value == -1:
        hash_value = -2
    return hash_value

4.5.

Python 2 ;

:

container.__iter__()

() Python/C API Python tp_iter

2 2 iterator protocol: () :

iterator.__iter__()

for in Python/C API Python tp_iter

iterator.__next__()

StopIteration Python/C APIPython tp_iternext

Python

__next__() StopIteration

4.6. list, tuple, range

3 : range

4.6.1.

collections.abc.Sequence ABC

s t n i j k x s

in not in + () * () [3]

x in s s x True , False (1)
x not in s s x False, True (1)
s + t s t (6)(7)
s * n n * s s n (2)(7)
s[i] s 0 i (3)
s[i:j] s i j (3)(4)
s[i:j:k] s i j k (3)(5)
len(s) s  
min(s) s  
max(s) s  
s.index(x[, i[, j]]) s x ( i j ) (8)
s.count(x) s x  

( )

:

  1. in not in (str, bytes, bytearray ) :

    >>> "gg" in "eggs"
    True
    
  2. 0 n 0 ( s ) s ; Python :

    >>> lists = [[]] * 3
    >>> lists
    [[], [], []]
    >>> lists[0].append(3)
    >>> lists
    [[3], [3], [3]]
    

    [[]] 1 [[]] * 3 3 () lists :

    >>> lists = [[] for i in range(3)]
    >>> lists[0].append(3)
    >>> lists[1].append(5)
    >>> lists[2].append(7)
    >>> lists
    [[3], [5], [7]]
    

    FAQ

  3. i j : len(s) + i len(s) + j -0 0

  4. s i j i <= k < j k i j len(s) len(s) i None 0 j None len(s) i j

  5. s i j k x = i + n*k n 0 <= n < (j-i)/k i, i+k, i+2*k, i+3*k j ( j ) k i j len(s) len(s) k i j len(s) - 1 len(s) - 1 i j None "" ( k ) k k None 1

  6. :

  7. (range )

  8. index x s ValueError i j s[i:j].index(x)

4.6.3.

collections.abc.MutableSequence ABC

s t x s ( bytearray 0 <= x <= 255 )

s[i] = x s i x  
s[i:j] = t s i j t  
del s[i:j] s[i:j] = []  
s[i:j:k] = t s[i:j:k] t (1)
del s[i:j:k] s[i:j:k]  
s.append(x) x (s[len(s):len(s)] = [x] )  
s.clear() s (del s[:] ) (5)
s.copy() s (s[:] ) (5)
s.extend(t) s += t s t ( s[len(s):len(s)] = t )  
s *= n s n (6)
s.insert(i, x) s i x (s[i:i] = [x] )  
s.pop([i]) s i (2)
s.remove(x) s s[i] == x (3)
s.reverse() s (4)

:

  1. t

  2. i -1

  3. remove s x ValueError

  4. reverse()

  5. clear() copy() (dict set )

    3.3 : clear() copy()

  6. n __index__() n s * n ;

4.6.4. (list)

()

class list([iterable])

:

  • : []
  • : [a][a, b, c]
  • : [x for x in iterable]
  • : list() list(iterable)

iterable iterable iterable iterable[:] list('abc') ['a', 'b', 'c'] list( (1, 2, 3) ) [1, 2, 3] []

sorted()

:

sort(*, key=None, reverse=False)

< ()

sort() (keyword-only arguments) :

key ( key=str.lower) None

2.x cmp key functools.cmp_to_key()

reverse True

( sorted() )

sort() ()

CPython : Python C ValueError

4.6.5. (tuple)

( enumerate() 2-) (set dict )

class tuple([iterable])

:

  • : ()
  • : a, (a,)
  • : a, b, c (a, b, c)
  • tuple() : tuple() tuple(iterable)

iterable iterable iterable tuple('abc') ('a', 'b', 'c') tuple( [1, 2, 3] ) (1, 2, 3) ()

f(a, b, c) f((a, b, c)) 3-

collections.namedtuple()

4.6.6. range

range for

class range(stop)
class range(start, stop[, step])

range ( int __index__ ) step 1 start 0 step 0 ValueError

step range r r[i] = start + step*i i >= 0 r[i] < stop

step range r r[i] = start + step*i i >= 0 r[i] > stop

r[0] range range

range sys.maxsize (len() ) OverflowError

range :

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]

range (range )

start

start ( 0)

stop

stop

step

step ( 1)

range list tuple range () (startstopstep range )

range collections.abc.Sequence ABC ( list, tuple, range ):

>>> r = range(0, 20, 2)
>>> r
range(0, 20, 2)
>>> 11 in r
False
>>> 10 in r
True
>>> r.index(10)
5
>>> r[5]
10
>>> r[:5]
range(0, 10, 2)
>>> r[-1]
18

== != range range ( range start, stop step range(0) == range(2, 1, 3) range(0, 3, 2) == range(0, 4, 2))

3.2 : ABC int

3.3 : () range '==' '!='

3.3 : start, stop step

4.7. str

Python str Unicode :

  • : '"" '
  • : "'' "
  • : '''''', """"""

("spam " "eggs") == "spam eggs"

r ("raw")

str

"character" 1 s s[0] == s[0:1]

str.join() io.StringIO

3.3 : Python 2 u r

class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')

object object str() encoding errors

encoding errors str(object) object.__str__() "" object object __str__() str() repr(object)

encoding errors object bytes-like object ( bytes bytearray) object bytes ( bytearray) str(bytes, encoding, errors) bytes.decode(encoding, errors) bytes.decode() buffer bytes buffer bytes, bytearray, memoryview (buffer Protocol)

encoding errors bytes str() 1 (Python -b ) :

>>> str(b'Zoot!')
"b'Zoot!'"

str str

4.7.1.

(str.format() ) C printf (printf )

(re )

str.capitalize()

str.casefold()

casefold casefold

casefold '' "ss" lower() '' casefold() "ss"

casefold Unicode Standard 3.13

3.3 .

str.center(width[, fillchar])

width fillchar ( ASCII ) width len(s)

str.count(sub[, start[, end]])

[start, end] sub start end

str.encode(encoding="utf-8", errors="strict")

'utf-8' errors 'strict' UnicodeError 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' codecs.register_error()

3.1 :

str.endswith(suffix[, start[, end]])

suffix True False suffix start end

str.expandtabs(tabsize=8)

1 (column) tabsize tabsize ( 8 0, 8, 16 ) 1 (\t) 1 () (\n \r) 0 (: ) 1

>>> '01\t012\t0123\t01234'.expandtabs()
'01      012     0123    01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01  012 0123    01234'
str.find(sub[, start[, end]])

s[start:end] sub start end sub -1

find() sub sub in :

>>> 'Py' in 'Python'
True
str.format(*args, **kwargs)

{}

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'

(int, float, float ) n (: '{:n}'.format(1234)) LC_CTYPE LC_NUMERIC 1 ASCII localeconv() decimal_point thousands_sep LC_CTYPE LC_NUMERIC

3.6.5 : n LC_CTYPE LC_NUMERIC

str.format_map(mapping)

str.format(**mapping) mapping dict mapping dict :

>>> class Default(dict):
...     def __missing__(self, key):
...         return key
...
>>> '{name} was born in {country}'.format_map(Default(name='Guido'))
'Guido was born in country'

3.2 .

str.index(sub[, start[, end]])

find() ValueError

str.isalnum()

1 c True : c.isalpha() c.isdecimal() c.isdigit() c.isnumeric()

str.isalpha()

1 Unicode "Letter" "Lm" "Lt" "Lu" "Ll" "Lo" Unicode "Alphabetic"

str.isdecimal()

1 U+0660 (ARABIC-INDIC DIGIT ZERO) Unicode "Nd"

str.isdigit()

1 10 Numeric_Type=Digit Numeric_Type=Decimal

str.isidentifier()

(identifier) (keyword)

def class keyword.iskeyword()

str.islower()

[4] 1

str.isnumeric()

1 Unicode U+2155 (VULGAR FRACTION ONE FIFTH) Numeric_Type=Digit Numeric_Type=Decimal Numeric_Type=Numeric

str.isprintable()

Unicode "Other" "Separator" ASCII space (0x20) ( repr() sys.stdout sys.stderr )

str.isspace()

1 Unicode "Other" "Separator" "WS" "B" "S"

str.istitle()

1

str.isupper()

[4] 1

str.join(iterable)

iterable iterable bytes TypeError

str.ljust(width[, fillchar])

width fillchar ( ASCII ) width len(s)

str.lower()

[4]

Unicode Standard 3.13

str.lstrip([chars])

chars chars None chars :

>>> '   spacious   '.lstrip()
'spacious   '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
static str.maketrans(x[, y[, z]])

str.translate()

1 Unicode () ( 1 ) Unicode () None

2 x y 3 None

str.partition(sep)

sep 3

str.replace(old, new[, count])

old new count count old

str.rfind(sub[, start[, end]])

s[start:end] sub start end sub -1

str.rindex(sub[, start[, end]])

rfind() sub ValueError

str.rjust(width[, fillchar])

width fillchar ( ASCII ) width len(s)

str.rpartition(sep)

sep 3

str.rsplit(sep=None, maxsplit=-1)

sep maxsplit maxsplit sep None rsplit() split()

str.rstrip([chars])

chars chars None chars :

>>> '   spacious   '.rstrip()
'   spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
str.split(sep=None, maxsplit=-1)

sep maxsplit maxsplit ( maxsplit+1 ) maxsplit -1 ()

sep ( '1,,2'.split(',') ['1', '', '2'] ) sep ( '1<>2<>3'.split('<>') ['1', '2', '3'] ) ['']

:

>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']

sep None None []

:

>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> '   1   2   3   '.split()
['1', '2', '3']
str.splitlines([keepends])

keepends

universal newlines

\n
\r
\r\n +
\v or \x0b
\f or \x0c
\x1c
\x1d
\x1e
\x85 (C1 )
\u2028
\u2029

3.2 : \v \f

:

>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

split() sep :

>>> "".splitlines()
[]
>>> "One line\n".splitlines()
['One line']

split('\n') :

>>> ''.split('\n')
['']
>>> 'Two lines\n'.split('\n')
['Two lines', '']
str.startswith(prefix[, start[, end]])

prefix True False prefix start end

str.strip([chars])

chars chars None chars :

>>> '   spacious   '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'

chars chars :

>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'
str.swapcase()

s.swapcase().swapcase() == s

str.title()

:

>>> 'Hello world'.title()
'Hello World'

:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

:

>>> import re
>>> def titlecase(s):
...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."
str.translate(table)

__getitem__() mapping sequence Unicode () Unicode 1 None LookupError

str.maketrans()

codecs

str.upper()

Return a copy of the string with all the cased characters [4] converted to uppercase. Note that str.upper().isupper() might be False if s contains uncased characters or if the Unicode category of the resulting character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, titlecase).

Unicode Standard 3.13

str.zfill(width)

width ASCII '0' ('+'/'-') '0' width len(s)

:

>>> "42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'

4.7.2. printf

: % () format % values (format ) format % values C sprintf()

format values [5] values

2 :

  1. '%'
  2. () ( (somename))
  3. ()
  4. () '*' () values
  5. () '.' () '*' () values
  6. ()

% (), '%' :

>>> print('%(language)s has %(number)03d quote types.' %
...       {'language': "Python", "number": 2})
Python has 002 quote types.

* (* )

:

Flag
'#' () ""
'0'
'-' ('0' '0' )
' ' () ()
'+' ('+' '-') ("" )

(h, l, L) Python %ld %d

:

'd' 10  
'i' 10  
'o' 8 (1)
'u' 'd' (6)
'x' 16 () (2)
'X' 16 () (2)
'e' () (3)
'E' () (3)
'f' 10 (3)
'F' 10 (3)
'g' -4 10 (4)
'G' -4 10 (4)
'c' ()  
'r' (Python repr() ) (5)
's' (Python str() ) (5)
'a' (Python ascii() ) (5)
'%' '%'  

:

  1. : # 8 ('0o')

  2. : # 16 '0x' '0X' ( 'x' 'X' )

  3. 6

  4. 0

    6

  5. N N

  6. PEP 237

Python %s '\0'

3.1 : 1e50 %f %g

4.8. bytes, bytearray, memoryview

bytes bytearray memoryview

array 32 IEEE754

4.8.1.

bytes ASCII bytes ASCII

class bytes([source[, encoding[, errors]]])

bytes b :

  • : b'still allows embedded "double" quotes'
  • : b"still allows embedded 'single' quotes".
  • 3: b'''3 single quotes''', b"""3 double quotes"""

bytes () ASCII 127 bytes

bytes r bytes

While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256 (attempts to violate this restriction will trigger ValueError. This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption).

bytes :

  • 0 bytes : bytes(10)
  • iterable : bytes(range(20))
  • : bytes(obj)

bytes

16 2 1 16 bytes

classmethod fromhex(string)

bytes bytes 16 2 ASCII

>>> bytes.fromhex('2Ef0 F1f2  ')
b'.\xf0\xf1\xf2'

bytes 16

hex()

1 2 16

>>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'

3.5 .

bytes () bytes b b[0] b[0:1] 1 bytes ( 1 )

bytes repr (b'...') bytes([46, 46, 46]) bytes list(b)

Python 2.x : Python 2.x 8bit (2.x ) Unicode Python 8bit Unicode Python 3.x 8-bit Unicode bytes

4.8.2. bytearray

bytearray bytes

class bytearray([source[, encoding[, errors]]])

bytearray :

  • : bytearray()
  • 0: bytearray(10)
  • iterable : bytearray(range(20))
  • : bytearray(b'Hi!')

bytearray bytes bytearray bytes mutable

bytearray

16 2 1 16 bytearray

classmethod fromhex(string)

bytearray bytearray 16 2 ASCII

>>> bytearray.fromhex('2Ef0 F1f2  ')
bytearray(b'.\xf0\xf1\xf2')

bytearray 16

hex()

1 2 16

>>> bytearray(b'\xf0\xf1\xf2').hex()
'f0f1f2'

3.5 .

bytearray () bytearray b b[0] b[0:1] 1 bytearray ( 1 )

bytearray (bytearray(b'...')) bytearray([46, 46, 46]) bytearray list(b)

4.8.3. bytes bytearray

bytes bytearray bytes-like object bytes bytearray

bytes bytes bytearray :

a = "abc"
b = a.replace("a", "f")

:

a = b"abc"
b = a.replace(b"a", b"f")

bytes bytearray ASCII

ASCII ASCII

bytes bytearray

bytes.count(sub[, start[, end]])
bytearray.count(sub[, start[, end]])

[start, end] sub start end

bytes-like object 0 255

3.3 : 0 255

bytes.decode(encoding="utf-8", errors="strict")
bytearray.decode(encoding="utf-8", errors="strict")

'utf-8' errors errors 'strict' UnicodeError 'ignore' 'replace' codecs.register_error()

encoding str bytes-like object bytes bytearray

3.1 :

bytes.endswith(suffix[, start[, end]])
bytearray.endswith(suffix[, start[, end]])

suffix True False suffix start end

() bytes-like object

bytes.find(sub[, start[, end]])
bytearray.find(sub[, start[, end]])

s[start:end] sub sub start end sub -1

bytes-like object 0 255

find() sub sub (: ) in :

>>> b'Py' in b'Python'
True

3.3 : 0 255

bytes.index(sub[, start[, end]])
bytearray.index(sub[, start[, end]])

find() ValueError

bytes-like object 0 255

3.3 : 0 255

bytes.join(iterable)
bytearray.join(iterable)

iterable bytes bytearray iterable str bytes-like objects TypeError bytes bytearray

static bytes.maketrans(from, to)
static bytearray.maketrans(from, to)

bytes.translate() from to from to bytes-like objects

3.1 .

bytes.partition(sep)
bytearray.partition(sep)

sep 3 bytearray bytes bytearray

bytes-like object

bytes.replace(old, new[, count])
bytearray.replace(old, new[, count])

old new count count old

bytes-like object

bytearray

bytes.rfind(sub[, start[, end]])
bytearray.rfind(sub[, start[, end]])

s[start:end] sub start end sub -1

bytes-like object 0 255

3.3 : 0 255

bytes.rindex(sub[, start[, end]])
bytearray.rindex(sub[, start[, end]])

rfind() sub ValueError

bytes-like object 0 255

3.3 : 0 255

bytes.rpartition(sep)
bytearray.rpartition(sep)

sep 3 bytearray bytes bytearray

bytes-like object

bytes.startswith(prefix[, start[, end]])
bytearray.startswith(prefix[, start[, end]])

prefix True False prefix start end

() bytes-like object

bytes.translate(table, delete=b'')
bytearray.translate(table, delete=b'')

delete 256

bytes.maketrans()

table None :

>>> b'read this short text'.translate(None, b'aeiou')
b'rd ths shrt txt'

3.6 : delete

bytes bytearray ASCII bytearray

bytes.center(width[, fillbyte])
bytearray.center(width[, fillbyte])

width fillbyte ( ASCII ) bytes width len(s)

bytearray

bytes.ljust(width[, fillbyte])
bytearray.ljust(width[, fillbyte])

width fillbyte ( ASCII ) bytes width len(s)

bytearray

bytes.lstrip([chars])
bytearray.lstrip([chars])

chars ASCII chars None ASCII : chars :

>>> b'   spacious   '.lstrip()
b'spacious   '
>>> b'www.example.com'.lstrip(b'cmowz.')
b'example.com'

bytes-like object

bytearray

bytes.rjust(width[, fillbyte])
bytearray.rjust(width[, fillbyte])

width fillbyte ( ASCII ) bytes width len(s)

bytearray

bytes.rsplit(sep=None, maxsplit=-1)
bytearray.rsplit(sep=None, maxsplit=-1)

sep maxsplit maxsplit sep None ASCII rsplit() split()

bytes.rstrip([chars])
bytearray.rstrip([chars])

chars ASCII chars None ASCII : chars :

>>> b'   spacious   '.rstrip()
b'   spacious'
>>> b'mississippi'.rstrip(b'ipz')
b'mississ'

bytes-like object

bytearray

bytes.split(sep=None, maxsplit=-1)
bytearray.split(sep=None, maxsplit=-1)

sep maxsplit maxsplit ( maxsplit+1 ) maxsplit -1 ()

sep ( b'1,,2'.split(b',') [b'1', b'', b'2'] ) sep ( b'1<>2<>3'.split(b'<>') [b'1', b'2', b'3'] ) [b''] [bytearray(b'')] sep bytes-like object

:

>>> b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>> b'1,2,3'.split(b',', maxsplit=1)
[b'1', b'2,3']
>>> b'1,2,,3,'.split(b',')
[b'1', b'2', b'', b'3', b'']

sep None ASCII ASCII []

:

>>> b'1 2 3'.split()
[b'1', b'2', b'3']
>>> b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>> b'   1   2   3   '.split()
[b'1', b'2', b'3']
bytes.strip([chars])
bytearray.strip([chars])

chars ASCII chars None ASCII : chars :

>>> b'   spacious   '.strip()
b'spacious'
>>> b'www.example.com'.strip(b'cmowz.')
b'example'

bytes-like object

bytearray

bytes bytearray ASCII bytearray

bytes.capitalize()
bytearray.capitalize()

ASCII ASCII

bytearray

bytes.expandtabs(tabsize=8)
bytearray.expandtabs(tabsize=8)

(column) (tab size) ASCII 1 ASCII tabsize ( 8 0 8 16 ) 1 ASCII (b'\t') 1 ASCII ASCII ASCII (b'\n' b'\r') 0 : 1 :

>>> b'01\t012\t0123\t01234'.expandtabs()
b'01      012     0123    01234'
>>> b'01\t012\t0123\t01234'.expandtabs(4)
b'01  012 0123    01234'

bytearray

bytes.isalnum()
bytearray.isalnum()

ASCII true false ASCII b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ASCII b'0123456789'

:

>>> b'ABCabc1'.isalnum()
True
>>> b'ABC abc1'.isalnum()
False
bytes.isalpha()
bytearray.isalpha()

ASCII true false ASCII b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

:

>>> b'ABCabc'.isalpha()
True
>>> b'ABCabc1'.isalpha()
False
bytes.isdigit()
bytearray.isdigit()

ASCII true false ASCII b'0123456789'

:

>>> b'1234'.isdigit()
True
>>> b'1.23'.isdigit()
False
bytes.islower()
bytearray.islower()

ASCII ASCII true false

:

>>> b'hello world'.islower()
True
>>> b'Hello world'.islower()
False

ASCII b'abcdefghijklmnopqrstuvwxyz' ASCII b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

bytes.isspace()
bytearray.isspace()

ASCII true false ASCII b' \t\n\r\x0b\f' ()

bytes.istitle()
bytearray.istitle()

ASCII true false bytes.title()

:

>>> b'Hello World'.istitle()
True
>>> b'Hello world'.istitle()
False
bytes.isupper()
bytearray.isupper()

ASCII ASCII true false

:

>>> b'HELLO WORLD'.isupper()
True
>>> b'Hello world'.isupper()
False

ASCII b'abcdefghijklmnopqrstuvwxyz' ASCII b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

bytes.lower()
bytearray.lower()

ASCII

:

>>> b'Hello World'.lower()
b'hello world'

ASCII b'abcdefghijklmnopqrstuvwxyz' ASCII b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

bytearray

bytes.splitlines(keepends=False)
bytearray.splitlines(keepends=False)

ASCII universal newlines keepends

:

>>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
[b'ab c', b'', b'de fg', b'kl']
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
[b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']

split() sep : :

>>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
([b''], [b'Two lines', b''])
>>> b"".splitlines(), b"One line\n".splitlines()
([], [b'One line'])
bytes.swapcase()
bytearray.swapcase()

ASCII

:

>>> b'Hello World'.swapcase()
b'hELLO wORLD'

ASCII b'abcdefghijklmnopqrstuvwxyz' ASCII b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

str.swapcase() bin.swapcase().swapcase() == bin Unicode ASCII

bytearray

bytes.title()
bytearray.title()

ASCII

:

>>> b'Hello world'.title()
b'Hello World'

ASCII b'abcdefghijklmnopqrstuvwxyz' ASCII b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

:

>>> b"they're bill's friends from the UK".title()
b"They'Re Bill'S Friends From The Uk"

:

>>> import re
>>> def titlecase(s):
...     return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0:1].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase(b"they're bill's friends.")
b"They're Bill's Friends."

bytearray

bytes.upper()
bytearray.upper()

ASCII

:

>>> b'Hello World'.upper()
b'HELLO WORLD'

ASCII b'abcdefghijklmnopqrstuvwxyz' ASCII b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

bytearray

bytes.zfill(width)
bytearray.zfill(width)

width ASCII b'0' (b'+'/b'-') b'0' bytes width len(seq)

:

>>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'

bytearray

4.8.4. printf bytes

()

bytes (bytes/bytearray) : % () bytes format % values (format bytes ) format % values C sprintf()

format values [5] values : format ()

2 :

  1. '%'
  2. () ( (somename))
  3. ()
  4. () '*' () values
  5. () '.' () '*' () values
  6. ()

% () bytes '%' :

>>> print(b'%(language)s has %(number)03d quote types.' %
...       {b'language': b"Python", b"number": 2})
b'Python has 002 quote types.'

* (* )

:

Flag
'#' () ""
'0'
'-' ('0' '0' )
' ' () ()
'+' ('+' '-') ("" )

(h, l, L) Python %ld %d

:

'd' 10  
'i' 10  
'o' 8 (1)
'u' 'd' (8)
'x' 16 () (2)
'X' 16 () (2)
'e' () (3)
'E' () (3)
'f' 10 (3)
'F' 10 (3)
'g' -4 10 (4)
'G' -4 10 (4)
'c' 1 ( 1 bytes/bytearray )  
'b' (buffer protocol __bytes__() ) (5)
's' 's' 'b' Python 2/3 (6)
'a' (Python repr(obj).encode('ascii','backslashreplace) ) (5)
'r' 'r' 'a' Python 2/3 (7)
'%' '%'  

:

  1. : # 8 ('0o')

  2. : # 16 '0x' '0X' ( 'x' 'X' )

  3. 6

  4. 0

    6

  5. N N

  6. b'%s' 3.x

  7. b'%r' 3.x

  8. PEP 237

bytearray

3.5 .

4.8.5.

memoryview Python

class memoryview(obj)

obj memoryview obj bytes bytearray

memoryview obj bytes bytearray array.array

len(view) tolist view.ndim = 0 1 view.ndim = 1 itemsize

memoryview :

>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103
>>> v[1:4]
<memory at 0x7f3ddc9f4350>
>>> bytes(v[1:4])
b'bce'

format struct 1 1 ndim ndim

format :

>>> import array
>>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
>>> m = memoryview(a)
>>> m[0]
-11111111
>>> m[-1]
44444444
>>> m[::2].tolist()
[-11111111, -33333333]

:

>>> data = bytearray(b'abcefg')
>>> v = memoryview(data)
>>> v.readonly
False
>>> v[0] = ord(b'z')
>>> data
bytearray(b'zbcefg')
>>> v[1:4] = b'123'
>>> data
bytearray(b'z123fg')
>>> v[2:3] = b'spam'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: memoryview assignment: lvalue and rvalue have different structures
>>> v[2:6] = b'spam'
>>> data
bytearray(b'z1spam')

'B', 'b', 'c' () 1 hash(m) == hash(m.tobytes()) :

>>> v = memoryview(b'abcefg')
>>> hash(v) == hash(b'abcefg')
True
>>> hash(v[2:4]) == hash(b'ce')
True
>>> hash(v[::-2]) == hash(b'abcefg'[::-2])
True

3.3 : 1 'B', 'b', 'c' 1

3.4 : memoryview collections.abc.Sequence

3.5 :

memoryview :

__eq__(exporter)

memoryview PEP 3118 shape struct

tolist() struct v.tolist() == w.tolist() v == w :

>>> import array
>>> a = array.array('I', [1, 2, 3, 4, 5])
>>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])
>>> c = array.array('b', [5, 3, 1])
>>> x = memoryview(a)
>>> y = memoryview(b)
>>> x == a == y == b
True
>>> x.tolist() == a.tolist() == y.tolist() == b.tolist()
True
>>> z = y[::-2]
>>> z == c
True
>>> z.tolist() == c.tolist()
True

struct () :

>>> from ctypes import BigEndianStructure, c_long
>>> class BEPoint(BigEndianStructure):
...     _fields_ = [("x", c_long), ("y", c_long)]
...
>>> point = BEPoint(100, 200)
>>> a = memoryview(point)
>>> b = memoryview(point)
>>> a == point
False
>>> a == b
False

memoryview v is w v == w

3.3 :

tobytes()

bytes

>>> m = memoryview(b"abc")
>>> m.tobytes()
b'abc'
>>> bytes(m)
b'abc'

tobytes() struct

hex()

2 16 :

>>> m = memoryview(b"abc")
>>> m.hex()
'616263'

3.5 .

tolist()

>>> memoryview(b'abc').tolist()
[97, 98, 99]
>>> import array
>>> a = array.array('d', [1.1, 2.2, 3.3])
>>> m = memoryview(a)
>>> m.tolist()
[1.1, 2.2, 3.3]

3.3 : tolist() struct native

release()

memoryview ( bytearray )release() ()

ValueError ( release() ):

>>> m = memoryview(b'abc')
>>> m.release()
>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object

with :

>>> with memoryview(b'abc') as m:
...     m[0]
...
97
>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object

3.2 .

cast(format[, shape])

memoryview shape shape [byte_length//new_itemsize] 1 memoryview 1 -> C C -> 1 : contiguous

struct ('B', 'b', 'c')

1D/long 1D/unsigned byte :

>>> import array
>>> a = array.array('l', [1,2,3])
>>> x = memoryview(a)
>>> x.format
'l'
>>> x.itemsize
8
>>> len(x)
3
>>> x.nbytes
24
>>> y = x.cast('B')
>>> y.format
'B'
>>> y.itemsize
1
>>> len(y)
24
>>> y.nbytes
24

1D/unsigned byte 1D/char :

>>> b = bytearray(b'zyz')
>>> x = memoryview(b)
>>> x[0] = b'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: memoryview: invalid value for format "B"
>>> y = x.cast('c')
>>> y[0] = b'a'
>>> b
bytearray(b'ayz')

1D/byte 3D/int 1D/signed char :

>>> import struct
>>> buf = struct.pack("i"*12, *list(range(12)))
>>> x = memoryview(buf)
>>> y = x.cast('i', shape=[2,2,3])
>>> y.tolist()
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
>>> y.format
'i'
>>> y.itemsize
4
>>> len(y)
2
>>> y.nbytes
48
>>> z = y.cast('b')
>>> z.format
'b'
>>> z.itemsize
1
>>> len(z)
48
>>> z.nbytes
48

1D/unsigned char 2D/unsigned long :

>>> buf = struct.pack("L"*6, *list(range(6)))
>>> x = memoryview(buf)
>>> y = x.cast('L', shape=[2,3])
>>> len(y)
2
>>> y.nbytes
48
>>> y.tolist()
[[0, 1, 2], [3, 4, 5]]

3.3 .

3.5 :

:

obj

memoryview :

>>> b  = bytearray(b'xyz')
>>> m = memoryview(b)
>>> m.obj is b
True

3.3 .

nbytes

nbytes == product(shape) * itemsize == len(m.tobytes()). len(m) :

>>> import array
>>> a = array.array('i', [1,2,3,4,5])
>>> m = memoryview(a)
>>> len(m)
5
>>> m.nbytes
20
>>> y = m[::2]
>>> len(y)
3
>>> y.nbytes
12
>>> len(y.tobytes())
12

:

>>> import struct
>>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)])
>>> x = memoryview(buf)
>>> y = x.cast('d', shape=[3,4])
>>> y.tolist()
[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]
>>> len(y)
3
>>> y.nbytes
96

3.3 .

readonly

format

(struct ) memoryview ( tolist())

3.3 : 'B' struct memoryview(b'abc')[0] == b'abc'[0] == 97

itemsize

memoryview :

>>> import array, struct
>>> m = memoryview(array.array('H', [32000, 32001, 32002]))
>>> m.itemsize
2
>>> m[0]
32000
>>> struct.calcsize('H') == m.itemsize
True
ndim

shape

N ndim

3.3 : ndim = 0 None

strides

ndim

3.3 : ndim = 0 None

suboffsets

PIL

c_contiguous

C : contiguous

3.3 .

f_contiguous

Fortran: contiguous

3.3 .

contiguous

: contiguous

3.3 .

4.9. set set, frozenset

set hashable () ( dict, list, tuple collections )

x in set, len(set), for x in set

set frozenset 2 set add() remove() frozenset

set (frozenset ) set : {'jack', 'sjoerd'}

:

class set([iterable])
class frozenset([iterable])

iterable set frozenset frozenset iterable

set frozenset :

len(s)

s (s )

x in s

x s

x not in s

x s

isdisjoint(other)

other True (disjoint)

issubset(other)
set <= other

set other

set < other

set other set <= other and set != other

issuperset(other)
set >= other

other set

set > other

set other set >= other and set != other

union(*others)
set | other | ...

set other

intersection(*others)
set & other & ...

set other

difference(*others)
set - other - ...

set other

symmetric_difference(other)
set ^ other

set other

copy()

s

union(), intersection(), difference(), symmetric_difference(), issubset(), issuperset() set('abc') & 'cbs' set('abc').intersection('cbs')

set frozenset () () ()

set frozenset set('abc') == frozenset('abc') set('abc') in set([frozenset('abc')]) True

False : a<b, a==b, a>b.

list.sort()

(hashable)

set frozenset : frozenset('ab') | set('bc') frozenset

set frozenset :

update(*others)
set |= other | ...

other set

intersection_update(*others)
set &= other & ...

set other set

difference_update(*others)
set -= other | ...

other set

symmetric_difference_update(other)
set ^= other

set

add(elem)

elem set

remove(elem)

elem set elem set KeyError

discard(elem)

elem set

pop()

s KeyError

clear()

set

update(), intersection_update(), difference_update(), symmetric_difference_update()

__contains__(), remove(), discard() elem frozenset elem frozenset

4.10. dict

(mapping) (hashable) (dictionary) ( list, set, tuple collections )

(hashable) () : ( 1 1.0 ) ()

key: value : {'jack': 4098, 'sjoerd': 4127} {4098: 'jack', 4127: 'sjoerd'} dict

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

iterable iterable 2 2 2

{"one": 1, "two": 2, "three": 3} :

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

Python

():

len(d)

d

d[key]

d key key KeyError

__missing__() key d[key] key d[key] __missing__(key) __missing__() __missing__() KeyError __missing__() :

>>> class Counter(dict):
...     def __missing__(self, key):
...         return 0
>>> c = Counter()
>>> c['red']
0
>>> c['red'] += 1
>>> c['red']
1

collections.Counter __missing__ collections.defaultdict

d[key] = value

d[key] value

del d[key]

d d[key] key KeyError

key in d

d key True False

key not in d

not key in d

iter(d)

iter(d.keys())

clear()

copy()

classmethod fromkeys(seq[, value])

seq value

fromkeys() value None

get(key[, default])

key key default default None KeyError

items()

((key, value) )

keys()

pop(key[, default])

key default default key KeyError

popitem()

(key, value)

popitem() popitem() KeyError

setdefault(key[, default])

key default key default default None

update([other])

other None

update() / (2) /: d.update(red=1, blue=2)

values()

(key, value) ('<', '<=', '>=', '>') TypeError

4.10.1.

dict.keys(), dict.values(), dict.items()

yield :

len(dictview)

iter(dictview)

((key, value) )

Python (value, key) zip() : pairs = zip(d.values(), d.keys()) pairs = [(v, k) for (k, v) in d.items()]

RuntimeError

x in dictview

x ( x (key, value) ) True

(key, value) () collections.abc.Set ( ==<^)

:

>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()

>>> # iteration
>>> n = 0
>>> for val in values:
...     n += val
>>> print(n)
504

>>> # keys and values are iterated over in the same order
>>> list(keys)
['eggs', 'bacon', 'sausage', 'spam']
>>> list(values)
[2, 1, 1, 500]

>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['spam', 'bacon']

>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
>>> keys ^ {'sausage', 'juice'}
{'juice', 'sausage', 'bacon', 'spam'}

4.11.

Python with :

contextmanager.__enter__()

with as

(file object) __enter__() open() with

decimal.localcontext() 10, with 10

contextmanager.__exit__(exc_type, exc_val, exc_tb)

() with None

with with with

__exit__()

Python contextlib

Python (generator) contextlib.contextmanager (decorator) contextlib.contextmanager __enter__() __exit__()

Python/C API Python Python

4.12.

1 2

4.12.1. (module)

: m.name m name m (import ; import foo foo foo () )

__dict__ __dict__ (m.__dict__['a'] = 1 m.a 1 m.__dict__ = {} ) __dict__

<module 'sys' (built-in)> <module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>

4.12.2.

4.12.3.

: func(argument-list)

: ()

4.12.4.

: ( append() )

() (bound method) (instance method) self 2 m.__self__ m.__func__ m(arg-1, arg-2, ..., arg-n) m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)

(meth.__func__) AttributeError :

>>> class C:
...     def method(self):
...         pass
...
>>> c = C()
>>> c.method.whoami = 'my name is method'  # can't set on the method
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'method' object has no attribute 'whoami'
>>> c.method.__func__.whoami = 'my name is method'
>>> c.method.whoami
'my name is method'

4.12.5.

"" Python compile() __code__ code

exec() eval() ()

4.12.6.

type() types

: <class 'int'>

4.12.7.

None () type(None)()

None

4.12.8. Ellipsis

( (slicing) )Ellipsis Ellipsis () type(Ellipsis)() Ellipsis

Ellipsis ...

4.12.9. NotImplemented

NotImplemented type(NotImplemented)()

NotImplemented

4.12.10.

False True () () 0 1 bool() ( )

False True

4.12.11.

4.13.

dir()

object.__dict__

()

instance.__class__

class.__bases__

definition.__name__

definition.__qualname__

3.3 .

class.__mro__

class.mro()

__mro__

class.__subclasses__()

:

>>> int.__subclasses__()
[<class 'bool'>]

[1] Python ()
[2] [1, 2] [1.0, 2.0]
[3]
[4](1, 2, 3, 4) "Lu" (Letter, uppercase ()) "Ll" (Letter, lowercase ()) "Lt" (Lettertitlecase ())
[5](1, 2) values