"print s"与"print [s]"中使用的编码不同?

Yar*_*tov 6 python unicode

当我在IPython笔记本中执行以下操作时

s='½'
s
print s
print [s]
Run Code Online (Sandbox Code Playgroud)

我知道了

'\xc2\xbd'
½
['\xc2\xbd']
Run Code Online (Sandbox Code Playgroud)
  1. 这里发生了什么?
  2. 如何打印Unicode字符串列表?(即我想看['½'])

编辑 所以从评论,看起来不同的是"打印s"使用s.__str__和"s","打印[s]"使用它的s.__repr__

Kas*_*mvd 6

您可以使用repr函数创建包含列表的可打印表示的字符串,然后使用string-escape编码解码您的字符串,该编码将返回字符串的字节字符串.然后通过打印字节字符串,您的终端将通过其默认编码(通常为UTF8)自动对其进行编码:

>>> print repr([s]).decode('string-escape')
['½']
Run Code Online (Sandbox Code Playgroud)

但请注意,因为在python 3.X中我们只有unicode,你不需要使用这个技巧:

Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> s='½'
>>> print ([s])
['½']
Run Code Online (Sandbox Code Playgroud)

有关python编码的更多信息,请阅读https://docs.python.org/2.4/lib/standard-encodings.html