.


:




:

































 

 

 

 





- ; - . Unicode (string). --0--255 bytes.

>>> by = b'abcd\x65' ①
>>> by
b'abcde'
>>> type(by) ②
<class 'bytes'>
>>> len(by) ③
5
>>> by += b'\xff' ④
>>> by
b'abcde\xff'
>>> len(by) ⑤
6
>>> by[0] ⑥
97
>>> by[0] = 102 ⑦
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

  • ① bytes " " b''. ASCII , \x00 \xff (0-255).
  • ② - bytes.
  • ③ , len().
  • ④ , +. bytes.
  • ⑤ 5- 6- .
  • ⑥ , . , . 0 255.
  • ⑦ . - . , (+), , , bytes bytearray.

 

>>> by = b'abcd\x65'
>>> barr = bytearray(by) ①
>>> barr
bytearray(b'abcde')
>>> len(barr) ②
5
>>> barr[0] = 102 ③
>>> barr
bytearray(b'fbcde')

  • ① bytes bytearray bytearray().
  • ② , bytes, bytearray.
  • ③ , bytearray. 0 255.

, , .

>>> by = b'd'
>>> s = 'abcde'
>>> by + s ①
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat bytes to str
>>> s.count(by) ②
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'bytes' object to str implicitly
>>> s.count(by.decode('ascii')) ③
1

  • ① . .
  • ② , . - . " , "? . Python 3 .
  • ③ " , ".


: bytes decode(), , . encode(), , bytes. : ASCII . , , (-Unicode) .

>>> a_string = '深入 Python' ①
>>> len(a_string)
9
>>> by = a_string.encode('utf-8') ②
>>> by
b'\xe6\xb7\xb1\xe5\x85\xa5 Python'
>>> len(by)
13
>>> by = a_string.encode('gb18030') ③
>>> by
b'\xc9\xee\xc8\xeb Python'
>>> len(by)
11
>>> by = a_string.encode('big5') ④
>>> by
b'\xb2`\xa4J Python'
>>> len(by)
11
>>> roundtrip = by.decode('big5') ⑤
>>> roundtrip
'深入 Python'
>>> a_string == roundtrip
True

  • ① . 9 .
  • ② bytes. 13 . , a_string UTF-8.
  • ③ bytes. 11 . , a_string GB18030.
  • ④ bytes. 11 . , a_string Big5.
  • ⑤ . . , by Big5. .




:


: 2016-11-18; !; : 598 |


:

:

, , . , .
==> ...

1554 - | 1390 -


© 2015-2024 lektsii.org - -

: 0.007 .