More Than Five
More Than Five

Reputation: 10429

Convert Strings as Bytes to String

I read the first few bytes of a JPEG

f = open(filename, 'rb')
firstTwoBytes = f.read(2)
if firstTwoBytes != '\xff\xd8':

firstTwoBytes iny my debugger is: bytes: b'\xff\xd8' which is correct?

So my String comparison fails. How best to fix this?

Thanks

Upvotes: 0

Views: 249

Answers (2)

Harry.Chen
Harry.Chen

Reputation: 1610

Try this:

if firstTwoBytes != b'\xff\xd8':

Upvotes: 2

ElmoVanKielmo
ElmoVanKielmo

Reputation: 11315

So, compare to binary not to the string:

f = open(filename, 'rb')
firstTwoBytes = f.read(2)
if firstTwoBytes != b'\xff\xd8':

Upvotes: 1

Related Questions