【问题标题】:Python what's the difference between str(u'a') and u'a'.encode('utf-8')Python str(u'a') 和 u'a'.encode('utf-8') 有什么区别
【发布时间】:2012-08-27 21:02:31
【问题描述】:

作为标题,是否有理由不使用 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'>

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

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

也是python 3中的Unicode对象

【问题讨论】:

    标签: python unicode


    【解决方案1】:

    当您编写str(u'a') 时,它会使用默认编码 将Unicode 字符串转换为字节字符串(除非您遇到changing it 的麻烦)将是ASCII。

    第二个版本将字符串显式编码为 UTF-8。

    如果您尝试使用包含非 ASCII 字符的字符串,则差异会更加明显。第二个版本仍然有效:

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

    第一个版本会给出异常:

    >>> str(u'€')
    
    回溯(最近一次通话最后):
      文件“”,第 1 行,在
        str(u'€')
    UnicodeEncodeError:'ascii' 编解码器无法在位置 0 编码字符 u'\x80':序数不在范围内(128)
    

    【讨论】:

    • if i do = 'abc' 如何得到变量 a 的 ascii
    猜你喜欢
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 2013-12-16
    • 2017-05-07
    • 2017-06-22
    相关资源
    最近更新 更多