【问题标题】:How to convert string with bytes value back to bytes?如何将带有字节值的字符串转换回字节?
【发布时间】:2020-02-05 00:01:22
【问题描述】:

我有一个程序,我将 python check_output 输出写入文件。我忘记将编码设置为“utf-8”,所有输出都以字节为单位。我已将这些字节值写入文件。我现在的文件中有一些字符串,例如“ b' math \xf0\x9d ”,其中包含 ASCII 和十六进制。如何仅获取 ASCII 值并将十六进制值(例如 \xf0\x9d)转换为其原始值?

要回答这个问题,我需要一种将带有字节值的字符串转换回字节的方法。在下面的示例中, opt 是字节, temp 是字符串。如何将 temp 转换为 opt 再次?

更多细节:这是我最初想要运行的代码。我在变量 opt 中得到的有十六进制值。我希望通过将其转换为字符串,我会摆脱它们,但它不起作用。

latex = "a+b"
opt = check_output(["latexmlmath", "--quiet", "--cmml=-", latex])
temp = str(opt)
# also tried
temp = str(opt).encode("utf-8")

opt 和 temp 值为:

b'<?xml version="1.0" encoding="UTF-8"?>\n<math xmlns="http://www.w3.org/1998/Math/MathML" alttext="a+b" display="block">\n  <apply>\n    <plus/>\n    <ci>\xf0\x9d\x91\x8e</ci>\n    <ci>\xf0\x9d\x91\x8f</ci>\n  </apply>\n</math>\n'
b'<?xml version="1.0" encoding="UTF-8"?>\n<math xmlns="http://www.w3.org/1998/Math/MathML" alttext="a+b" display="block">\n  <apply>\n    <plus/>\n    <ci>\xf0\x9d\x91\x8e</ci>\n    <ci>\xf0\x9d\x91\x8f</ci>\n  </apply>\n</math>\n'

【问题讨论】:

    标签: python ascii


    【解决方案1】:

    你想要opt.decode('utf-8');在没有第二个 (encoding) 参数的情况下对 bytes 对象调用 str 只会获得 bytes 对象的 repr。如果您有来自此类转换的数据,您可以将其转换回原始bytes 对象with ast.literal_eval,然后对结果执行预期的decode。示例:

    import ast
    
    baddata = 'b\'<?xml version="1.0" encoding="UTF-8"?>\\n<math xmlns="http://www.w3.org/1998/Math/MathML" alttext="a+b" display="block">\\n  <apply>\\n    <plus/>\\n    <ci>\\xf0\\x9d\\x91\\x8e</ci>\\n    <ci>\\xf0\\x9d\\x91\\x8f</ci>\\n  </apply>\\n</math>\\n\''
    gooddata = ast.literal_eval(baddata).decode('utf-8')
    print(gooddata)
    

    输出:

    <?xml version="1.0" encoding="UTF-8"?>
    <math xmlns="http://www.w3.org/1998/Math/MathML" alttext="a+b" display="block">
      <apply>
        <plus/>
        <ci>?</ci>
        <ci>?</ci>
      </apply>
    </math>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      • 2020-07-09
      • 1970-01-01
      相关资源
      最近更新 更多