sys.stdout.encoding、locale.getpreferredencoding() 和 sys.getdefaultencoding() 之间有什么区别?

use*_*285 5 python encoding locale codepages sys

我对 python 很陌生,对这种编码的东西很困惑。到目前为止,我已经阅读了以下类型的“编码”:

import sys
import locale

print (sys.stdout.encoding)
print (locale.getpreferredencoding())
print (sys.getdefaultencoding())
Run Code Online (Sandbox Code Playgroud)

输出:

utf8
cp1252
utf-8
Run Code Online (Sandbox Code Playgroud)

有什么不同?

小智 1

简而言之,编码是数据在内存中存储的方式。不同的方式允许更多的字符和信息。如需深入解释,我们非常欢迎您阅读http://kunststube.net/encoding/Wikipedia

在 python 中,您可以通过物理调用编码类型或使用任何编码函数来更改事物的存储方式。

sys.stdout.encoding对于您的 python3.x 环境,和 之间没有区别sys.getdefaultencoding()。它们都使用 8 位代码单元(最标准)。而首选编码locale.getpreferredencoding()( cp1252) 是 Windows 版本的latin1.

请注意,如果您想获得任何方法/功能的快速反馈,您可以随时使用帮助命令。

例子:

>>> import locale
>>> help(locale.getpreferredencoding)
Run Code Online (Sandbox Code Playgroud)

输出:

Help on function getpreferredencoding in module locale:

getpreferredencoding(do_setlocale=True)
    Return the charset that the user is likely using,
    according to the system configuration.
(END)
Run Code Online (Sandbox Code Playgroud)