4.
None
4.1.
__bool__() False __len__() 0 [1] :
- :
NoneFalse - :
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) |
:
notnot a == bnot (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
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//20(-1)//2-11//(-2)-1(-1)//(-2)0"nan" "inf" "+" "-" (Not a Number (NaN))
Python
pow(0, 0)0 ** 0109Unicode (Nd)Ndhttp://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 () |
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 |
:
-
ValueError - n
pow(2, n) - 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
x0x.bit_length()2**(k-1) <= abs(x) < 2**kkabs(x)k = 1 + int(log(abs(x), 2))x0x.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
OverflowErrorbyteorder byteorder
"big"byteorder"little"sys.byteordersigned 2 signed
FalseOverflowErrorsignedFalse3.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.byteordersigned 2
3.2 .
4.4.3.
numbers.Real (abstract base class)
-
float.as_integer_ratio() OverflowError(NaN)ValueError
16 16 Python 2 10 10 16 (numerical work)
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 / nnPinvmod(n, P)nP()hash(x)m * invmod(n, P) % Px = m / nnP(m)nPhash(x)sys.hash_info.infx = m / nhash(x)-hash(-x)-1-2-
sys.hash_info.inf-sys.hash_info.infsys.hash_info.nannan () ( nan ) - (
complex)zhash(z.real) + sys.hash_info.imag * hash(z.imag)2**sys.hash_info.widthrange(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1))-1-2
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.__next__() StopIterationPython/C APIPythontp_iternext
Python
4.5.1.
Python generator () __iter__() __iter__() __next__() () yield
4.6. list, tuple, range
4.6.1.
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 |
:
innot in(str,bytes,bytearray) :>>> "gg" in "eggs" True
0n0( s ) s ; Python :>>> lists = [[]] * 3 >>> lists [[], [], []] >>> lists[0].append(3) >>> lists [[3], [3], [3]]
[[]]1[[]] * 33 ()lists:>>> lists = [[] for i in range(3)] >>> lists[0].append(3) >>> lists[1].append(5) >>> lists[2].append(7) >>> lists [[3], [5], [7]]
i j :
len(s) + ilen(s) + j-00s i j
i <= k < jk i jlen(s)len(s)iNone0jNonelen(s)i js i j k
x = i + n*kn0 <= n < (j-i)/ki,i+k,i+2*k,i+3*kj ( j ) k i jlen(s)len(s)k i jlen(s) - 1len(s) - 1i jNone"" ( k ) k kNone1:
(
range)indexx sValueErrori js[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) |
:
t
i
-1removes xValueErrorreverse()-
3.3 :
clear()copy() n
__index__()ns * 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][]-
sort(*, key=None, reverse=False) <()sort()(keyword-only arguments) :key (
key=str.lower)None2.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-- :
4.6.6. range
-
class
range(stop) -
class
range(start, stop[, step]) range (
int__index__) step1start0step 0ValueErrorstep range
rr[i] = start + step*ii >= 0r[i] < stopstep range
rr[i] = start + step*ii >= 0r[i] > stopr[0]range rangerange
sys.maxsize(len())OverflowErrorrange :
>>> 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 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 '==' '!='
- range linspace
4.7. str
Python str Unicode :
- :
'"" ' - :
"'' " - :
'''''',""""""
("spam " "eggs") == "spam eggs"
"character" 1 s s[0] == s[0:1]
3.3 : Python 2 u r
-
class
str(object='') -
class
str(object=b'', encoding='utf-8', errors='strict') object object
str()encoding errorsencoding errors
str(object)object.__str__()"" object object__str__()str()repr(object)encoding errors object bytes-like object (
bytesbytearray) objectbytes(bytearray)str(bytes, encoding, errors)bytes.decode(encoding, errors)bytes.decode()buffer bytes buffer bytes, bytearray, memoryview (buffer Protocol)encoding errors
bytesstr()1 (Python-b) :>>> str(b'Zoot!') "b'Zoot!'"
strstr
4.7.1.
(str.format() ) C printf (printf )
(re )
-
str.casefold() casefold casefold
casefold
''"ss"lower()''casefold()"ss"casefold Unicode Standard 3.13
3.3 .
-
str.encode(encoding="utf-8", errors="strict") 'utf-8'errors'strict'UnicodeError'ignore','replace','xmlcharrefreplace','backslashreplace'codecs.register_error()3.1 :
-
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.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_CTYPELC_NUMERIC1 ASCIIlocaleconv()decimal_pointthousands_sepLC_CTYPELC_NUMERIC3.6.5 :
nLC_CTYPELC_NUMERIC
-
str.format_map(mapping) str.format(**mapping)mappingdictmappingdict :>>> 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.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.stdoutsys.stderr)
-
str.isupper() [4] 1
-
str.lstrip([chars]) chars chars
Nonechars :>>> ' spacious '.lstrip() 'spacious ' >>> 'www.example.com'.lstrip('cmowz.') 'example.com'
-
str.rindex(sub[, start[, end]]) rfind()subValueError
-
str.rstrip([chars]) chars chars
Nonechars :>>> ' 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
NoneNone[]:
>>> '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
\n\r\r\n+ \vor\x0b\for\x0c\x1c\x1d\x1e\x85(C1 ) \u2028\u20293.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.strip([chars]) chars chars
Nonechars :>>> ' 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.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 1NoneLookupError
-
str.upper() Return a copy of the string with all the cased characters [4] converted to uppercase. Note that
str.upper().isupper()might beFalseifscontains 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
4.7.2. printf
() str.format()
: % () format % values (format ) format % values C sprintf()
format values [5] values
2 :
-
'%' - () (
(somename)) - ()
- ()
'*'() values - ()
'.'()'*'() values - ()
% (), '%' :
>>> 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) |
'%' |
'%' |
:
:
#8 ('0o'):
#16'0x''0X'('x''X')-
6
0
6
NN
Python %s '\0'
3.1 : 1e50 %f %g
4.8. 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
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 triggerValueError. 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)
16 2 1 16 bytes
-
classmethod
fromhex(string) bytesbytes 16 2 ASCII>>> bytes.fromhex('2Ef0 F1f2 ') b'.\xf0\xf1\xf2'
bytes 16
- :
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
-
class
bytearray([source[, encoding[, errors]]]) bytearray :
- :
bytearray() - 0:
bytearray(10) - iterable :
bytearray(range(20)) - :
bytearray(b'Hi!')
bytearray bytes bytearray bytes mutable
16 2 1 16 bytearray
-
classmethod
fromhex(string) bytearraybytearray 16 2 ASCII>>> bytearray.fromhex('2Ef0 F1f2 ') bytearray(b'.\xf0\xf1\xf2')
bytearray 16
- :
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
strbytes-like object bytes bytearray3.1 :
-
bytes.endswith(suffix[, start[, end]]) -
bytearray.endswith(suffix[, start[, end]]) suffix
TrueFalsesuffix start end
-
bytes.find(sub[, start[, end]]) -
bytearray.find(sub[, start[, end]]) s[start:end]sub sub start end sub-1bytes-like object 0 255
3.3 : 0 255
-
bytes.index(sub[, start[, end]]) -
bytearray.index(sub[, start[, end]]) -
bytes-like object 0 255
3.3 : 0 255
-
bytes.join(iterable) -
bytearray.join(iterable) iterable bytes bytearray iterable
strbytes-like objectsTypeErrorbytes bytearray
-
static
bytes.maketrans(from, to) -
static
bytearray.maketrans(from, to) bytes.translate()from to from to bytes-like objects3.1 .
-
bytes.replace(old, new[, count]) -
bytearray.replace(old, new[, count]) old new count count old
bytearray
-
bytes.rfind(sub[, start[, end]]) -
bytearray.rfind(sub[, start[, end]]) s[start:end]sub start end sub-1bytes-like object 0 255
3.3 : 0 255
-
bytes.rindex(sub[, start[, end]]) -
bytearray.rindex(sub[, start[, end]]) rfind()subValueErrorbytes-like object 0 255
3.3 : 0 255
-
bytes.startswith(prefix[, start[, end]]) -
bytearray.startswith(prefix[, start[, end]]) prefix
TrueFalseprefix start end
-
bytes.translate(table, delete=b'') -
bytearray.translate(table, delete=b'') delete 256
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 )
byteswidthlen(s)bytearray
-
bytes.ljust(width[, fillbyte]) -
bytearray.ljust(width[, fillbyte]) width fillbyte ( ASCII )
byteswidthlen(s)bytearray
-
bytes.lstrip([chars]) -
bytearray.lstrip([chars]) chars ASCII chars
NoneASCII : chars :>>> b' spacious '.lstrip() b'spacious ' >>> b'www.example.com'.lstrip(b'cmowz.') b'example.com'
bytearray
-
bytes.rjust(width[, fillbyte]) -
bytearray.rjust(width[, fillbyte]) width fillbyte ( ASCII )
byteswidthlen(s)bytearray
-
bytes.rstrip([chars]) -
bytearray.rstrip([chars]) chars ASCII chars
NoneASCII : chars :>>> b' spacious '.rstrip() b' spacious' >>> b'mississippi'.rstrip(b'ipz') b'mississ'
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
NoneASCII 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
NoneASCII : chars :>>> b' spacious '.strip() b'spacious' >>> b'www.example.com'.strip(b'cmowz.') b'example'
bytearray
bytes bytearray 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'ASCIIb'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'ASCIIb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-
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'ASCIIb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-
bytes.lower() -
bytearray.lower() ASCII
:
>>> b'Hello World'.lower() b'hello world'
ASCII
b'abcdefghijklmnopqrstuvwxyz'ASCIIb'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'ASCIIb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'str.swapcase()bin.swapcase().swapcase() == binUnicode ASCIIbytearray
-
bytes.title() -
bytearray.title() ASCII
:
>>> b'Hello world'.title() b'Hello World'
ASCII
b'abcdefghijklmnopqrstuvwxyz'ASCIIb'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'ASCIIb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'bytearray
-
bytes.zfill(width) -
bytearray.zfill(width) width ASCII
b'0'(b'+'/b'-')b'0'byteswidthlen(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 :
-
'%' - () (
(somename)) - ()
- ()
'*'() values - ()
'.'()'*'() values - ()
% () 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) |
'%' |
'%' |
:
:
#8 ('0o'):
#16'0x''0X'('x''X')-
6
0
6
NNb'%s'3.xb'%r'3.x
bytearray
3.5 .
4.8.5.
memoryview Python
-
class
memoryview(obj) obj
memoryviewobjbytesbytearraymemoryviewobjbytesbytearrayarray.arraylen(view)tolistview.ndim = 01view.ndim = 1itemsize>>> v = memoryview(b'abcefg') >>> v[1] 98 >>> v[-1] 103 >>> v[1:4] <memory at 0x7f3ddc9f4350> >>> bytes(v[1:4]) b'bce'
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.Sequence3.5 :
-
__eq__(exporter) memoryview PEP 3118 shape
structtolist()structv.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 wv == w3.3 :
-
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]
-
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 : contiguousstruct('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 :
:
-
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 .
-
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
-
shape N
ndim3.3 : ndim = 0
None
-
c_contiguous C : contiguous
3.3 .
-
f_contiguous Fortran: 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
setfrozensetfrozensetiterable-
len(s) s (s )
-
x in s x s
-
x not in s x s
-
set < other set other
set <= other and set != other
-
set > other set other
set >= other and set != other
union(),intersection(),difference(),symmetric_difference(),issubset(),issuperset()set('abc') & 'cbs'set('abc').intersection('cbs')setfrozensetset('abc') == frozenset('abc')set('abc') in set([frozenset('abc')])TrueFalse:a<b,a==b,a>b.(hashable)
setfrozenset:frozenset('ab') | set('bc')frozenset-
remove(elem) elem set elem set
KeyError
-
pop() s
KeyError
update(),intersection_update(),difference_update(),symmetric_difference_update()__contains__(),remove(),discard()elemfrozensetelem 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__()keyd[key]keyd[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]keyKeyError
-
key in d d key
TrueFalse
-
key not in d not key in d
-
iter(d) iter(d.keys())
-
classmethod
fromkeys(seq[, value]) seq value
fromkeys()valueNone
-
get(key[, default]) key key default default
NoneKeyError
-
pop(key[, default]) key default default key
KeyError
-
update([other]) other
Noneupdate()/ (2) /:d.update(red=1, blue=2)
(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()]
-
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__() -
(file object) __enter__()
open()withdecimal.localcontext()10,with10
-
contextmanager.__exit__(exc_type, exc_val, exc_tb) ()
withNone
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.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'