当前位置: 动力学知识库 > 问答 > 编程问答 >

python 3.x - Convert string with bytes to byte string

问题描述:

I need to convert a string with bytes (string view) to byte object in Python.

string = input() # string = '\xff\x00B'

bs = samefunc(string) # typeof(bs) == bytes, len(bs) == 3

print(bs[0]) # b'\xff'

print(bs[1]) # b'\x00'

print(bs[2]) # b'B'

In my app the string input is so large the self parser will be very slow.

网友答案:

You can use eval (or ast.literal_eval, which is more secure if the input is not 100% in your hands):

s = input() # s = '\\xff\\x00B'
bs = eval("b'%s'" % s) # typeof(bs) == bytes, len(bs) == 3
print(bs[0]) # 255
print(bs[1]) # 0
print(bs[2]) # 66
分享给朋友:
您可能感兴趣的文章:
随机阅读: