【Python 2.7】str和unicode的互相转换,摘自《Effective Python》
生活随笔
收集整理的這篇文章主要介紹了
【Python 2.7】str和unicode的互相转换,摘自《Effective Python》
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
str 和 unicode
以下摘自《Effective Python》
python3 有兩種表示字符序列的類型:bytes 和 str。前者的實(shí)例包含原始的8位值;后者的實(shí)例包含Unicode字符。
python2 中也有兩種表示字符序列的類型,分別叫做 str 和 unicode 。與 python3 不同的是,str 的實(shí)例包含原始的8位值,而 unicode 的實(shí)例,則包含 Unicode 字符。
下圖輔助理解。
以下可復(fù)制:
def to_unicode(unicode_or_str):if isinstance(unicode_or_str, str):value = unicode_or_str.decode('utf-8')else:value = unicode_or_strreturn value # Instance of unicodedef to_str(unicode_or_str):if isinstance(unicode_or_str, unicode):value = unicode_or_str.encode('utf-8')else:value = unicode_or_strreturn value # Instance of str示例:解決Python2.7無法輸出中文的問題
對(duì)比示例:
json_all = getExampleData(args)for key in json_all.keys():curlogger.info(to_str(key)) # 使用 to_str,將 unicode 轉(zhuǎn)換成 strcurlogger.info(json_all.keys()) # 不轉(zhuǎn)換成 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
總結(jié)
以上是生活随笔為你收集整理的【Python 2.7】str和unicode的互相转换,摘自《Effective Python》的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【MySQL distinct的使用】如
- 下一篇: 【Python】Effective Py