gpt4 book ai didi

python - ipython 和 python 处理我的字符串的方式不同,为什么?

转载 作者:太空狗 更新时间:2023-10-30 02:34:34 24 4
gpt4 key购买 nike

在 python (2.7.1) 中:

>>> x = u'$€%'
>>> x.find('%')
2
>>> len(x)
3

而在 ipython 中:

>>> x = u'$€%'
>>> x.find('%')
4
>>> len(x)
5

这是怎么回事?


编辑:包括从下面的评论中请求的额外信息

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

python

>>> 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

最佳答案

@nye17 调用 setdefaultencoding() 正式不是一个好主意(它在第一次使用后出于某种原因从 sys 中删除)。一个常见的罪魁祸首是 gtk,它会导致各种问题,因此如果 IPython 导入了 gtk,sys.getdefaultencoding() 将返回 utf8。 IPython 本身不设置默认编码。

@wim 请问您使用的是哪个版本的 IPython? 0.11 中的部分重大改革是修复了许多 unicode 错误,但确实出现了更多错误(现在主要在 Windows 上)。

我在 IPython 0.11 中运行了你的测试用例,IPython 和 Python 的行为看起来是一样的,所以我认为这个错误已经修复。

相关值:

  • sys.stdin.encoding = utf8
  • sys.getdefaultencoding() = ascii
  • 测试平台:Ubuntu 10.04+Python2.6.5, OSX 10.7+Python2.7.1

至于解释,基本上 IPython 不承认输入可以是 unicode。在 IPython 0.10 中,不考虑多字节 utf8 输入,因此每个字节 = 1 个字符,您可以通过以下方式查看:

In [1]: x = '$€%'

In [2]: x
Out[2]: '$\xe2\x82\xac%'

In [3]: y = u'$€%'

In [4]: y
Out[4]: u'$\xe2\x82\xac%'# wrong!

然而,应该发生的,以及 0.11 中确实发生的,是 y == x.decode(sys.stdin.encoding),而不是 repr(y) == 'u'+repr(x).

关于python - ipython 和 python 处理我的字符串的方式不同,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7593454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com