簡體   English   中英

如何在python2中將str類型的unicode字符串轉換為真正的unicode字符串?

[英]How to convert a unicode string with str type to a real unicode string in python2?

我正在嘗試將str字符串'\中\國'為unicode u'\中\國' 在python3中是一樣的東西,但是在python2.7中怎么做呢?

我試過解碼,編碼,str,字節,unicode等,但是它們都沒有用。

a = '\u4e2d\u56fd'
b = u'\u4e2d\u56fd'
print a
print b

上面代碼的結果是

\u4e2d\u56fd
中國

我要做的就是將a轉換為b。

多謝小費!

您需要使用raw_unicode_escape編解碼器。 例如:

a = '\u4e2d\u56fd'
a = a.decode('raw_unicode_escape')
print a
中國

您應該在.py文件的標頭中寫# -*- coding: utf-8 -*-

# -*- coding: utf-8 -*-
a = '\u4e2d\u56fd'
print a

或嘗試

import sys
reload(sys)
sys.setdefaultencoding('utf8')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM