python中的字符串编码

gri*_*yvp 0 python unicode codepages

在python中,字符串可以是unicode(utf-16和utf-8)和单字节,具有不同的编码(cp1251,cp1252等).是否可以检查编码字符串是什么?例如,

time.strftime( "%b" )
Run Code Online (Sandbox Code Playgroud)

将返回一个文本名称为月份的字符串.在MacOS下,返回的字符串将是utf-16,在Windows下使用英语本地,它将是带有ascii编码的单字节,而在具有非英语语言环境的Windows下,它将通过语言环境的代码页进行编码,例如cp1251.我该如何处理这些字符串?

Lup*_*uch 5

字符串不存储任何编码信息,您只需在转换为/从unicode或打印到输出设备时指定一个:

import locale
lang, encoding = locale.getdefaultlocale()
mystring = u"blabla"
print mystring.encode(encoding)
Run Code Online (Sandbox Code Playgroud)

UTF-8 不是 unicode,它是 unicode编码为单字节字符串.

最佳实践是在python端使用unicode,使用unicode可逆编码(如UTF-8)存储字符串,并仅为用户输出转换为花式语言环境.