擅长:python、mysql、java
<p>当您输入<code>"我"</code>时,Python解释器会从终端获得该字符在本地字符集中的表示形式,由于<code>""</code>,它将其逐字节存储在字符串中。在我的UTF-8系统上,这是<code>'\xe6\x88\x91'</code>。在你的,它是<code>'\xce\xd2'</code>,因为你使用的是GB2312。这解释了变量<code>a</code>的值。在</p>
<p>当您输入<code>u"我"</code>时,Python解释器不知道<code>我</code>字符是哪个编码的。它的作用与普通字符串几乎相同:它将字符的字节存储在Unicode字符串中,将每个字节解释为Unicode码位,因此结果<code>u'\xce\xd2'</code>(或者,在我的框中,<code>u'\xe6\x88\x91'</code>)。在</p>
<p>这个问题只存在于交互式解释器中。当您编写Python脚本或模块时,您可以<a href="http://docs.python.org/tutorial/interpreter.html#source-code-encoding">specify the encoding</a>靠近顶部,Unicode字符串就会显示出来。E、 g.在我的系统中,下面的命令会将单词<em>liberté</em>打印两次:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
print(u"liberté")
print("liberté")
</code></pre>