2012-01-26 61 views
0

我的系統:XP + python27 編解碼器, XP GBK;蟒蛇27 ASCII如何讓我的角色?

>>> a = '你好'  
>>> a 
'\xc4\xe3\xba\xc3' 
>>> print a 
你好 
>>> '\xc4\xe3\xba\xc3'.decode('gbk') 
u'\u4f60\u597d' 
>>> '\xc4\xe3\xba\xc3'.encode('gbk') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal 
not in range(128) 

我怎樣才能得到 「你好」 從 '\ XC4 \ XE3 \ XBA \ XC3'?

+0

你能在擴展question.language等? – Damien

回答

0

您的Python shell無法打印gbk編碼的字符串。它在那裏,你無法打印它。

+0

+1。 OP應該嘗試打印爲UTF-8。 –

6

這工作,因爲你解碼字節到Unicode:

'\xc4\xe3\xba\xc3'.decode('gbk') 

這不,因爲你想編碼字節(這已經被編碼):

'\xc4\xe3\xba\xc3'.encode('gbk') 

Python 2中的錯誤消息在這裏沒有幫助,但是您應該只使用unicode字符串上的編碼:

u'\u4f60\u597d'.encode('gbk') # Gets you back the bytes you had before. 

在Python 2中,只要在交互式提示符下執行a,就會在轉義字符串中顯示非ascii字符(如\xc3\u4f60)。你可以做print a來顯示字符。或者使用Python 3,它將顯示包括unicode字符的字符串。

+0

我無法得到你好! – user1142618

+2

@ user1142618:我認爲你應該從閱讀這篇文章開始:http://www.joelonsoftware.com/articles/Unicode.html –

0

他指編碼進行打印時,不顯示需要

>>> a = u'\u4f60\u597d'.encode('gbk') 
>>> print a 
��� 
>>> a 
'\xc4\xe3\xba\xc3' 

但是如果指定:

>>> a = '\xe4\xbd\xa0\xe5\xa5\xbd' 
>>> print a 
你好 

你應該使用:

>>> c = '\xe4\xbd\xa0\xe5\xa5\xbd'.decode('gbk') 
>>> c 
u'\u6d63\u72b2\u30bd' 
>>> c = c.encode('gbk') 
>>> print c 
你好 
相關問題