'How to test individual characters of a bytes string object?

Let's say we want to test if the first character of b"hello" is a b"h":

s = b"hello"
print(s[0] == b"h")      # False   <-- this is the most obvious solution, but doesn't work
print(s[0] == ord(b"h"))  # True, but not very explicit

What is the most standard way to test if one character (not necessarily the first one) of a bytes-string is a given character, for example b"h"? (maybe there is an official PEP recommendation about this?)



Solution 1:[1]

(maybe there is an official PEP recommendation about this?)

If you mean PEP 8 then so far as I know it does not have any recommendations specific for bytes objects.

As accesing n-th element of bytes does return integer I would propose following solution

s = b"hello"
print(s[0] == b"h"[0])  # True

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1