plugwash
plugwash

Reputation: 10514

best way to test an ASCII character in a python3 bytes object

I have a bytes object and want to test if a particular ASCII character is in a particular position.

I nievely wrote code like

if b[i] == b"\n":

The problem is this doesn't work, it turns out after some experimenting with repr that while indexing a string produces a string indexing a bytes produces a number and comparing a number with a bytes always returns false.

I fixed this by doing

if b[i] == b"\n"[0]:

I have realised I could also do

if b[i:i+1] == b"\n":

Is there a reason to prefer one approach over the other?

Is there a neater soloution?

Upvotes: 1

Views: 48

Answers (1)

wim
wim

Reputation: 363153

A neater solution, perhaps, would be to use ord, which returns a codepoint (integer):

>>> ord(b'\n')
10

That being said, the approach using a slice is quite fine too. Just be wary that slicing out of bounds returns an empty string, rather than triggering an IndexError.

Upvotes: 2

Related Questions