将字节字符串转换为字节

huangapple go评论76阅读模式
英文:

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 = &quot;b&#39;\x00\x00\x00\x00\x07\x80\x00\x03&#39;&quot;
type(result) -&gt; &lt;class &#39;str&#39;&gt;

How do I convert it to bytes? It should be like this:

a = b&#39;\x00\x00\x00\x00\x07\x80\x00\x03&#39;

type(a) -&gt; &lt;class &#39;bytes&#39;&gt;

答案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 = &quot;b&#39;\x00\x00\x00\x00\x07\x80\x00\x03&#39;&quot;
result = bytes(result[2:-1], &quot;latin1&quot;) # result[2:-1] remove b&#39;&#39; at the beginning and end
#Or: result = result[2:-1].encode(&quot;latin1&quot;)

print(type(result)) # Return &lt;class &#39;bytes&#39;&gt;

答案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 = &quot;b&#39;\x00\x00\x00\x00\x07\x80\x00\x03&#39;&quot;
x = eval(a.encode(&quot;unicode-escape&quot;).decode())
print(type(x)) -&gt; bytes

Same thing for the exec function.

huangapple
  • 本文由 发表于 2023年2月26日 19:09:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75571560.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定