Basj
Basj

Reputation: 46247

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

Upvotes: 0

Views: 851

Answers (2)

Daweo
Daweo

Reputation: 36640

(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

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251478

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

Upvotes: 1

Related Questions