python2如何在内部处理字符串和unicode?

python2如何在内部处理字符串和unicode?,python,string,python-2.7,unicode,Python,String,Python 2.7,Unicode,我对python的unicode/str进程感到困惑。我在python2中遇到过一些情况 下面的句子写在一个py文件中,在idepycharm中使用utf8编码 打印“你好!%s”%u“中国" 打印“你好!%s“%”中国“ print u“你好!%s“%”中国“ 仅情况3引发解码错误: UnicodeDecodeError:“ascii”编解码器无法解码位置中的字节0xe4 0:序号不在范围内(128) 谁能告诉我python是如何处理这句话的?为什么会有结果?如果删除print语句,您可以看到

我对python的unicode/str进程感到困惑。我在python2中遇到过一些情况

下面的句子写在一个py文件中,在idepycharm中使用utf8编码

  • 打印“你好!%s”%u“中国"
  • 打印“你好!%s“%”中国“
  • print u“你好!%s“%”中国“
  • 仅情况3引发解码错误:

    UnicodeDecodeError:“ascii”编解码器无法解码位置中的字节0xe4 0:序号不在范围内(128)


    谁能告诉我python是如何处理这句话的?为什么会有结果?

    如果删除print语句,您可以看到更多细节:

    >>> "hello! %s" % u"中国"
    u'hello! \u4e2d\u56fd'
    >>> "hello! %s" % "中国"
    'hello! \xe4\xb8\xad\xe5\x9b\xbd'
    >>> u"hello! %s" % "中国"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
    

    您可能会发现这篇文章很有帮助:,是由经验丰富的Ned Batchelder撰写的。好的,谢谢。我从您的回答中得到了两个信息。1.当所有的ByTestRing都是ByTestRing时,python不会将ByTestRing转换为unicode。是否有一些文档?2.第三种情况。该文件用utf8编码进行标记。python是如何以及为什么这样认为的是ASCIl编码。
    >>> u"hello! %s" % "中国".decode('utf-8')
    u'hello! \u4e2d\u56fd'