2012-08-27 47 views
8

作爲標題,有沒有理由不使用str()將unicode字符串轉換爲str?Python str(u'a')和u'a'.encode('utf-8')之間的區別是什麼

>>> str(u'a') 
'a' 
>>> str(u'a').__class__ 
<type 'str'> 
>>> u'a'.encode('utf-8') 
'a' 
>>> u'a'.encode('utf-8').__class__ 
<type 'str'> 
>>> u'a'.encode().__class__ 
<type 'str'> 

更新:感謝您的回答,也不知道如果我創建使用特殊字符的字符串它會自動轉換爲UTF-8

>>> a = '€' 
>>> a.__class__ 
<type 'str'> 
>>> a 
'\xe2\x82\xac' 

也就是在Python 3一個Unicode對象

回答

19

當你寫str(u'a')它的Unicode字符串轉換爲使用默認編碼它(除非你去的changing it麻煩)將是ASCII字節字符串。

第二個版本將字符串顯式編碼爲UTF-8。

如果您嘗試使用包含非ASCII字符的字符串,則區別更明顯。第二個版本將仍然工作:

>>> u'€'.encode('utf-8') 
'\xc2\x80' 

第一個版本將給出一個例外:

>>> str(u'€') 

Traceback (most recent call last): 
    File "", line 1, in 
    str(u'€') 
UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128) 
相關問題