Lavair
Lavair

Reputation: 946

How do I change the type of a string to a bytestring?

For example, I have '\x87' and I want b'\x87'.
I know, that there exists .encode(), but when I execute ('\x87').encode(), I get b'\xc2\x87' and not b'\x87'.
Is there any way to tell python that it should interpret the given string as a bytestring without possibly changing it in any way?

Upvotes: 2

Views: 41

Answers (2)

Marios Nikolaou
Marios Nikolaou

Reputation: 1336

Try this.

my_str = '\x87'
my_str_as_bytes = my_str.encode(encoding='latin')

Upvotes: 3

wovano
wovano

Reputation: 5092

One possible solution is:

bytes(ord(x) for x in '\x87')

Upvotes: 1

Related Questions