问题
For example given an arbitrary string. Could be chars
or just random bytes
:
string = '\xf0\x9f\xa4\xb1'
I want to output:
b'\xf0\x9f\xa4\xb1'
This seems so simple, but I could not find an answer anywhere. Of course just typing the b
followed by the string will do. But I want to do this runtime, or from a variable containing the strings of byte.
if the given string
was AAAA
or some known characters
I can simply do string.encode('utf-8')
, but I am expecting the string of bytes to just be random. Doing that to '\xf0\x9f\xa4\xb1'
( random bytes ) produces unexpected result b'\xc3\xb0\xc2\x9f\xc2\xa4\xc2\xb1'
.
There must be a simpler way to do this?
Edit:
I want to convert the string to bytes without using an encoding
回答1:
I found a working solution
import struct
def convert_string_to_bytes(string):
bytes = b''
for i in string:
bytes += struct.pack("B", ord(i))
return bytes
string = '\xf0\x9f\xa4\xb1'
print (convert_string_to_bytes(string))
)
output:
b'\xf0\x9f\xa4\xb1'
来源:https://stackoverflow.com/questions/51754731/python-convert-strings-of-bytes-to-byte-array