【发布时间】:2011-09-29 06:45:13
【问题描述】:
在 python (2.7.1) 中:
>>> x = u'$€%'
>>> x.find('%')
2
>>> len(x)
3
而在 ipython 中:
>>> x = u'$€%'
>>> x.find('%')
4
>>> len(x)
5
这是怎么回事?
编辑:包括从下面的 cmets 请求的附加信息
ipython
>>> import sys, locale
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding(locale.getdefaultlocale()[1])
>>> sys.getdefaultencoding()
'UTF8'
>>> x = u'$€%'
>>> x
u'$\xe2\x82\xac%'
>>> print x
$â¬%
>>> len(x)
5
蟒蛇
>>> import sys, locale
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding(locale.getdefaultlocale()[1])
>>> sys.getdefaultencoding()
'UTF8'
>>> x = u'$€%'
>>> x
u'$\u20ac%'
>>> print x
$€%
>>> len(x)
3
【问题讨论】:
-
如果你在 CPython 的命令行中输入
x <Enter>会发生什么?你的 shell 使用什么字符编码? -
print x给出$€%,而仅x给出u'$\u20ac%' -
sys.stdin.encoding is 'UTF-8'
-
这肯定是 ipython shell 中的一个错误。不过,它不应该影响您正在运行的程序。损坏的 Unicode 终端通常很常见(只需查看 Windows 控制台...),因此依靠能够以任何语言键入和打印 Unicode 到控制台的能力通常非常不确定。它可以在脚本本身和其他 IO 方法中正常工作。
标签: python string unicode encoding ipython