Polyglot CheatSheet - Bytes
Last Updated: 2022-04-04
1 byte = 8-bit integer, in the range 0 to 255
Python
bytes
is an immutable array of bytes (PyString)bytearray
is a mutable array of bytes (PyBytes)memoryview
is a bytes view on another object (PyMemory)
bytes
literal: b'...'
str
objects: hold character databytes
objects: hold raw bytes
Indexing returns a integer:
>>> a = b'asdf'
>>> a
b'asdf'
>>> a[0]
97
while str
returns a character:
>>> b = 'asdf'
>>> b
'asdf'
>>> b[0]
'a'
- Assigning or comparing an object that is not an integer to an element causes a TypeError exception.
- Assigning an element to a value outside the range 0 to 255 causes a ValueError exception.
string must comes with encoding
bytearray:
>>> a = bytearray("123", 'utf-8')
>>> a[0]
49
>>> a[1]
50
bytes:
>>> a = bytes('abc', 'utf-8')
>>> a
b'abc'