简体   繁体   中英

String variable as literal bytes

I'm reading in a config file. Say I end up with a configuration variable:

header = '\x42\x5a\x68'

I want to match this against binary files using startswith.

Unsurprisingly, I get a "TypeError startswith first arg must be bytes or a tuple of bytes, not str" , if I try to use this directly. How do I use this string? I don't want it encoded.

I have to read the string from a file. If there's some other way to go about this, I'm all ears. Thanks for reading!

How do I use this string? I don't want it encoded.

You must. Make a decision, either decode the string you get from the binary file or encode the header name. You can't mix those two types together.

See Text Vs. Data Instead Of Unicode Vs. 8-bit in the python docs, all mixing between these types (as it occurs in startswith too) will result in a TypeError .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM