【Python 2.7】str和unicode的互相转换,摘自《Effective Python》

str 和 unicode

以下摘自《Effective Python》

python3 有两种表示字符序列的类型:bytes 和 str。前者的实例包含原始的8位值;后者的实例包含Unicode字符。
python2 中也有两种表示字符序列的类型,分别叫做 str 和 unicode 。与 python3 不同的是,str 的实例包含原始的8位值,而 unicode 的实例,则包含 Unicode 字符。

下图辅助理解。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

以下可复制:

def to_unicode(unicode_or_str):
    if isinstance(unicode_or_str, str):
        value = unicode_or_str.decode('utf-8')
    else:
        value = unicode_or_str
    return value  # Instance of unicode


def to_str(unicode_or_str):
    if isinstance(unicode_or_str, unicode):
        value = unicode_or_str.encode('utf-8')
    else:
        value = unicode_or_str
    return value  # Instance of str

示例:解决Python2.7无法输出中文的问题

对比示例:

json_all = getExampleData(args)

for key in json_all.keys():
    curlogger.info(to_str(key))  # 使用 to_str,将 unicode 转换成 str
    
curlogger.info(json_all.keys())  # 不转换成 str,直接输出 unicode

输出log:

2019-12-21 21:36:46,871 - INFO: json_all.keys() = axisclass
2019-12-21 21:36:46,871 - INFO: json_all.keys() = 中文示例
2019-12-21 21:36:46,871 - INFO: json_all.keys() = timeseries
2019-12-21 21:36:46,875 - INFO: ['axisclass', u'\u4ed3\u5355\u6a61\u80f6', 'timeseries']

这样可以正常解码 unicode 字符,方便查看log

发布了552 篇原创文章 · 获赞 201 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/sinat_42483341/article/details/103648807