简体   繁体   中英

Python interpret bytearray as bytes

I have a question regarding the interpretation of a string as bytes

Within python, I have the situation that one variable contains eg this value

"bytearray(b'\x13\x02US')" 

this is unfortunately due to the behavior of a module I am using. My question is, how could i get this string into bytes?

I have tried stripping away the "bytearray(b'" and the "')" at the end, and use.encode() as a function, but the result then is:

b'\\x13\\x02US'

Which clearly escapes the \ in order to prevent the interpretation as bytes.

How could i get this converted into

b'\x13\x02US'

instead though?

Thank you very much!

You could use.decode().replace('\\', '\'), this way it replaces the double slashes with single ones. Either attache it after your.encode() function or do it on your string seperately.

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