Python str(u'a')和u'a'.encode('utf-8')之间的区别是什么?

Jam*_*Lin 8 python unicode

作为标题,是否有理由不使用str()将unicode字符串转换为str?

>>> 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'>
Run Code Online (Sandbox Code Playgroud)

更新:谢谢你的答案,也不知道我是否使用特殊字符创建一个字符串它会自动转换为utf-8

>>> a = '€'
>>> a.__class__
<type 'str'>
>>> a
'\xe2\x82\xac'
Run Code Online (Sandbox Code Playgroud)

也是python 3中的Unicode对象

Mar*_*ers 19

当你编写str(u'a')它时,使用默认编码将Unicode字符串转换为字节字符串(除非你遇到了改变它的麻烦)将是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)