Reputation: 1
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
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