我一直在使用 python 进行 ascii 到二进制的转换,但在解析结果时一直遇到问题。最后我想看看 Python 命令生成了什么。
输出中似乎插入了一个rouge 0xc2
(例如):
$ python -c 'print("\x80")' | xxd
00000000: c280 0a ...
事实上,无论在何处使用此类字节,都会发生这种情况:
$ python -c 'print("Test\x80Test2\x81")' | xxd
00000000: 5465 7374 c280 5465 7374 32c2 810a Test..Test2...
凭直觉,我在 UTF-8 上搜索了一下果然,U+0080
被编码为 0xc2 0x80
。显然,Python 冒昧地假设 \x80
我实际上意味着 U+0080
的编码。有没有办法更改此默认行为或以其他方式明确指示我打算包含单个字节 0x80
而不是 UTF 编码?
Python 3.6.2
最佳答案
Python 3 正确地将一个字符插入 str
中,它是字符串,而不是字节序列。
UTF8 是默认编码。如果您需要插入一个字节,则需要一种将该字符表示为字节的不同编码。
$ PYTHONIOENCODING=iso-8859-1 python3 -c 'print("\x80")' | xxd
00000000: 800a
PYTHONIOENCODING
If this is set before running the interpreter, it overrides the encoding used for stdin/stdout/stderr, in the syntax encodingname:errorhandler. Both the encodingname and the :errorhandler parts are optional and have the same meaning as in str.encode().
关于python - 为什么 Python 会自动将字符串中的十六进制编码为 UTF-8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45518925/