【发布时间】: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'
【问题讨论】: