0
b'1'[0]

The binary sequence of 1, when indexed is 49, I can't figure out why is it. Also the b'2'[0] is 50, what is the underlying binary sequence for the numbers?

2
  • Look up ASCII/Unicode codes. Commented Sep 10, 2021 at 11:34
  • Because ord('1') is 49. Likewise, chr(49) is '1'. There's a difference between characters (in a string) and integers. Commented Sep 10, 2021 at 11:35

1 Answer 1

1

What you have there is no a "binary sequence", it is a bytes literal.

>>> type(b'1')
<class 'bytes'>

A bytes object is an immutable sequence of single bytes, so all numbers in this sequence have to be in range(0, 256)`. You can construct it from a list of numbers as well:

>>> bytes([50, 33])     
b'2!'

So what is this b'' notation all about?

Well, sequences of bytes are often related to text. Not always, but often enough that Python supports a lot of string methods on bytes objects, like capitalize, index and split, as well as this convenient literal syntax where you can enter text, and have it be equivalent to series of bytes corresponding to that text encoded in ASCII. It's still an immutable sequence of numbers in range(0, 256) under the hood, though, which is why indexing a bytes object gives a number.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.