【问题标题】:Convert Stringed Bytes Back Into Bytes将字符串字节转换回字节
【发布时间】:2020-02-21 14:20:49
【问题描述】:

我正在做一个将一些字节保存为字符串的项目,但我似乎无法弄清楚如何将字节恢复为实际字节!

我有这个字符串:

"b'\x80\x03]q\x00(X\r\x00\x00\x00My First Noteq\x01X\x0e\x00\x00\x00My Second Noteq\x02e.'"

如你所见,对数据的 type() 函数返回的是字符串而不是字节:

<class 'str'>

如何将此字符串转换回字节?

感谢任何帮助,谢谢!

【问题讨论】:

  • 这能回答你的问题吗? string encoding and decoding?
  • 很遗憾,没有。
  • 为什么不呢?您需要对字符串进行编码
  • 如果我对字符串进行编码,id 只会得到一个 DOUBLE 编码的字符串!像这样:b"b'.....
  • 看起来你实际上有一个字符串,那么。而不是字节。请出示minimal reproducible example 说明您如何获取数据

标签: python-3.x


【解决方案1】:

试试:

x="b'\x80\x03]q\x00(X\r\x00\x00\x00My First Noteq\x01X\x0e\x00\x00\x00My Second Noteq\x02e.'"

y=x[2:-1].encode("utf-8")

>>> print(y)

b'\xc2\x80\x03]q\x00(X\r\x00\x00\x00My First Noteq\x01X\x0e\x00\x00\x00My Second Noteq\x02e.'

>>> print(type(y))

<class 'bytes'>

您刚刚将bytes 转换为没有编码的常规string - 所以您有多余的标签表明:b'...' - 您只需删除它们,python 将为您完成剩下的工作;)

【讨论】:

    【解决方案2】:

    在 python 3 中:

    >>> a=b'\x00\x00\x00\x00\x07\x80\x00\x03'
    >>> b = list(a)
    >>> b
    [0, 0, 0, 0, 7, 128, 0, 3]
    >>> c = bytes(b)
    >>> c
    b'\x00\x00\x00\x00\x07\x80\x00\x03'
    >>>
    

    【讨论】:

    • 感谢您的回复!尽管该代码在 Python3 中不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多