英文:
How to convert bytes string to bytes
问题
将数据库请求的字符串转换为字节,应该像这样:
result = b'\x00\x00\x00\x00\x07\x80\x00\x03'
type(result) # 返回 <class 'bytes'>
英文:
I have a string from a database request as follows:
result = "b'\x00\x00\x00\x00\x07\x80\x00\x03'"
type(result) -> <class 'str'>
How do I convert it to bytes? It should be like this:
a = b'\x00\x00\x00\x00\x07\x80\x00\x03'
type(a) -> <class 'bytes'>
答案1
得分: 1
You shouldn't use eval()
function unless you trust the input like greenegran0 answer, because it can make your code insecure.
You can use bytes()
class or encode()
function to convert it into bytes instead.
result = "b'\x00\x00\x00\x00\x07\x80\x00\x03'"
result = bytes(result[2:-1], "latin1") # result[2:-1] remove b'' at the beginning and end
Or: result = result[2:-1].encode("latin1")
print(type(result)) # Return <class 'bytes'>
英文:
You shouldn't use eval()
function unless you truth the input like greenegran0 answer, because it can make your code insecure.
You can use bytes()
class or encode()
function to convert it into bytes instead.
result = "b'\x00\x00\x00\x00\x07\x80\x00\x03'"
result = bytes(result[2:-1], "latin1") # result[2:-1] remove b'' at the beginning and end
#Or: result = result[2:-1].encode("latin1")
print(type(result)) # Return <class 'bytes'>
答案2
得分: -1
你可以使用 eval()
或 exec()
函数将一个字符串转换为你想要的任何 Python 对象。以下是一个示例:
a = "b'\x00\x00\x00\x00\x07\x80\x00\x03'"
x = eval(a.encode("unicode-escape").decode())
print(type(x)) # -> bytes
对于 exec
函数也是一样的。
英文:
From what I understood (I have a terrible understanding of english):
You can use the eval()
or the exec()
function to convert a string to any Python object you want.
Here's an example:
a = "b'\x00\x00\x00\x00\x07\x80\x00\x03'"
x = eval(a.encode("unicode-escape").decode())
print(type(x)) -> bytes
Same thing for the exec
function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论