1234
1234

Reputation: 1

How to transform str to bytes (not change every byte) in python?

for example,how to change s to b here?

s="\x00\x01\x02\x00\xad\xaa"
b=b"\x00\x01\x02\x00\xad\xaa"

I know str.encode() will return a encoded bytes, but it did not meet my expectations(because sometimes len(str)!=len(bytes)).

I read some method change str to bytes such as encode/decode, base64, but all it can't meet my expectations

Upvotes: 0

Views: 27

Answers (1)

Adid
Adid

Reputation: 1584

You can use python's built in encode method with raw_unicode_escape encoding to preserve literal escape sequences.

s = '\x00\x01\x02\x00\xad\xaa'
b = s.encode(encoding='raw_unicode_escape')
print(b)
>>> b'\x00\x01\x02\x00\xad\xaa'

Upvotes: 1

Related Questions