它有助於提供如下示例。這說明了操作環境(操作系統和Python版本):
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(unichr(1547))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u060b' in position 0: character maps to <undefined>
問題不在於轉換,而在於打印。在上述情況下,Windows控制檯使用cp437
編碼,並且不支持要打印的字符。
轉換工作正常,c
包含Unicode字符,這是AFGHANI SIGN
。
>>> c = unichr(1547)
>>> c
u'\u060b'
>>> import unicodedata as ud
>>> ud.name(c)
'AFGHANI SIGN'
如果你想讓它正確打印,一個方法是使用一個IDE PythonWin
從支持UTF-8編碼輸出pywin32
擴展:
PythonWin 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32.
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> unichr(1547)
u'\u060b'
>>> print(unichr(1547))
؋
另一種是寫輸出到一個UTF-8編碼的文件,並在記事本中打開結果:
with io.open('out.txt','w',encoding='utf8') as f:
f.write(unichr(1547)+unichr(402)+unichr(165))
輸出文件:
؋ƒ¥