当我在IPython笔记本中执行以下操作时
s='½'
s
print s
print [s]
Run Code Online (Sandbox Code Playgroud)
我知道了
'\xc2\xbd'
½
['\xc2\xbd']
Run Code Online (Sandbox Code Playgroud)
编辑
所以从评论,看起来不同的是"打印s"使用s.__str__和"s","打印[s]"使用它的s.__repr__
您可以使用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
| 归档时间: |
|
| 查看次数: |
184 次 |
| 最近记录: |