简体   繁体   中英

How to literally convert string to bytes?

I have this following key in my app, which although the prefix, it is saved as a string and not bytes ( <class 'str'> ).

b'-----BEGIN RSA PUBLIC KEY-----\nMBgCEQCc5QP2pLttRTltj9QFdn1DAgMBAAE=\n-----END RSA PUBLIC KEY-----\n'

I try to convert is into bytes string, using bytes() or.encode, but both returns the following format which is not the same:

b"b'-----BEGIN RSA PUBLIC KEY-----\\nMBgCEQCc5QP2pLttRTltj9QFdn1DAgMBAAE=\\n-----END RSA PUBLIC KEY-----\\n'" <class 'bytes'>

Any clue on how to tell my program to just take this string as it is and read it as bytes?

You can use the bytes(string, enc) function.

Assuming that you're using utf-8 this should work with python3.

_string = "Some String"
_string_as_bytes = bytes(_string, 'utf-8')

EDIT: But what you have is the console output and that is displayed as b'Some String' , but you had that stored as if you had run _string = "b'Some String'" so you needed a substring of the original that trimmed away b' and the trailing ' .

so if you _string = _string[2:len(_string)-1] then you get the substring with the delimiter removed. Console displays it as 'Some String' and then you can make the call to bytes(...) as above.

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