python3將unicode編碼字符串輸出漢字

python3 把str的unicode轉中文
  • 1、一般直接輸出是以下這樣的:
>>> print('\u722c\u866b')
>>> 爬蟲
  • 2、但是如果是以下這樣就不能正常的輸入漢字,
>>> print('uni722c'.replace("uni", r"\u"))
>>> \u722c
  • 3、python3以上取消了字符串的decode方法,所以你如果直接用str.decode(“utf-8”)的字符串轉爲unicode,會報如下錯誤AttributeError: ‘str’ object has no attribute ‘decode’
>>> print('uni722c'.replace("uni", r"\u").decode('unicode_escape'))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'
  • 4、解決方法如下:
>>> print('uni722c'.replace("uni", r"\u").encode('utf-8').decode('unicode_escape'))
>>>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章