python - 为什么 Python 会自动将字符串中的十六进制编码为 UTF-8?

标签 python python-3.x unicode

我一直在使用 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/

相关文章:

html - 如何用 HTML 编写此 RTL 布局?

python - 在同一函数中打开两个 url 时出错

python - 如何在Python中等待释放按钮

python - 如何循环 python 命令一定次数?

python - 如何将对象类型的列转换为 HexaDecimal

python - 如何判断一个字符串是否包含有效的 Python 代码

python3 - 使用断言的不好做法?

python-3.x - 如何使用 Youtube Data API v3 获取 YouTube channel 中的所有视频标题?

python - 如何将unicode字符串拆分为列表

c# - 在 C# .NET 应用程序上显示 ñ