1

Run across this:

import sys; print('Python %s on %s' % (sys.version, sys.platform))
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
b'\n' == b'\n'
True # well obviously
b'\n'[-1] == b'\n'
False # huh?
bytes(b'\n'[-1]) == b'\n'
False
b'\n'[-1] == 10
True

So it seems that when indexing in the byte array we get an integer value - why is this and how should I compare the values so I do not have to plugin the ascii value of the byte string element explicitly?

1
  • 1
    Not clear what you are trying to do, but b'\n'[-1] == ord('\n') evaluates to True. The elements of a bytes array are bytes -- which are integers in the range 0-255. Thinking of them as strings in Python 3 is a bit misleading. Commented May 27, 2020 at 11:58

1 Answer 1

1

When you do b'\n', you create an instance of bytes that contains one value 10.
When you access an element of an instance of bytes, an int is returned as expected (a byte is an 8 bits unsigned int).

Thus b'\n'[-1] == b'\n' being False makes sense, the value 10 is different from a bytes instance containing one byte

When you use the bytes constructor with an int, it creates a zero-filled bytes instance of the size you gave as input (python doc).

Thus bytes(b'\n'[-1]) == b'\n' also makes sense, a list of 10 bytes of value 0 is not equal to a list of only byte of value 10.

Hope it helps

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

1 Comment

Thanks - this in combination with the comment by @JohnColeman answers my question and tells me how I should compare without plugging in the int value explicitly

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.