2014-01-24 39 views
1

在Python 3.3的字符串,我試圖從截斷的Unicode值, 重建Unicode字符,然後打印到控制檯的字符。Python3:創建具有在反斜槓

例如,從「4E00」我要形成字符串「\ u4E00」。我曾嘗試:

base = '4E00' 
uni = r'\u' + base 
print(uni)  # getting '\u4E00', want: '一' 
print(repr(uni)) # '\\u4E00' 

有沒有一種方法,形成這種情況的一個轉義字符串如「\ u4E00」?

回答

1

用途:

chr(int(base, 16)) 

把一個十六進制值轉換爲Unicode字符。

\u轉義序列只能在字符串文字。您可能使用:

(br'\u' + base.encode('ascii')).decode('unicode_escape') 

但這是更詳細的比這個需要是。

演示:

>>> base = '4E00' 
>>> chr(int(base, 16)) 
'一' 
>>> (br'\u' + base.encode('ascii')).decode('unicode_escape') 
'一' 
2

記住\u後跟一個Unicode字符代碼僅在字符串中的事情。 r'\u' + '4E00'作爲一個Unicode字符沒有特殊含義,因爲它不是全部在一個字面上;它只是一個六字符的字符串。

所以你想採取一個Unicode換碼,因爲它會出現在一個Python字符串文字,然後解碼該成Unicode字符。你可以這樣做:

base = '4E00' 
uni = str(bytes(r'\u' + base, encoding="ascii"), encoding="unicode_escape") 

但它是很長的路要走各地(特別是因爲你必須把它轉換爲bytes第一,因爲它已經是Unicode的)。您的Unicode字符規格是十六進制的。因此,直接將其轉換爲整數,然後用chr()把它變成一個Unicode字符。

base = '4E00' 
uni = chr(int(base, 16))