Home > front end >  How to test individual characters of a bytes string object?
How to test individual characters of a bytes string object?

Time:02-22

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?)

CodePudding user response:

You could do s[:1] == b"h".

CodePudding user response:

(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
  • Related