1

Behaviour is showed in the code:

>>> b = bytes(b'asdf')
>>> print(type(b))
<class 'bytes'>
>>> print(type(b[0]))
<class 'int'>

Why when I get one byte from the bytes object like this b[0], it converts it to int.

Cipepote
  • 36
  • 1
  • 5
  • 1
    use slice to get it as bytes `type(b[:0])` – furas Apr 22 '21 at 11:41
  • 1
    you have the same with list `a = [1,2,3]` - `type(a)` gives `` and `type(a[0])` gives `` instead of `` but `type(a[:0])` still gives ``. Maybe the same is with `bytes` - it may means `"list of integers"` and when y – furas Apr 22 '21 at 11:44
  • 2
    This is the expected and [documented](https://docs.python.org/3/library/stdtypes.html#bytes-objects) behavior: "bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256" – Thierry Lathuille Apr 22 '21 at 11:45

1 Answers1

1

The bytes() function returns a bytes object. So, b in your example is an immutable sequence of bytes. Each element of the sequence is unsigned int and accessible via index.

Pouya Esmaeili
  • 1,265
  • 4
  • 11
  • 25