[英]How to convert string with bytes value back to bytes?
我有一个程序,我将 python check_output 输出写入文件。 我忘了将编码设置为“utf-8”,所有输出都以字节为单位。 我已将这些字节值写入文件。 我现在在我的文件中有一些字符串,如“ b' math \\xf0\\x9d ”,其中包含 ASCII 和十六进制。 如何仅获取 ASCII 值并将十六进制值(例如 \\xf0\\x9d)转换为其原始值?
为了回答这个问题,我需要一种将带有字节值的字符串转换回字节的方法。 在下面的例子中,opt 是字节,temp 是一个字符串。 如何将 temp 转换为再次选择?
更多细节:这是我最初想要运行的代码。 我在变量 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'
你想要opt.decode('utf-8')
; 在没有第二个( encoding
)参数的bytes
对象上调用str
只会获取bytes
对象的repr
。 如果您有来自此类转换的可用数据,您可以使用ast.literal_eval
将其转换回原始bytes
对象,然后对结果执行预期的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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.