Search code examples
pythonstringbytepep

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

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