一系列unicode文字

时间:2016-05-22 20:58:52

标签: python arrays python-2.7 unicode

我正在编写应该是Python 2.7和Python 3.3+兼容的代码。当尝试使用Python 2.7运行我的代码时,我遇到了以下问题。

我在unicode_literals的每个文件中导入__future__,但我无法使array功能正常工作。

from array import array
from __future__ import unicode_literals

尝试制作字符数组不起作用

array("c", "test")
> TypeError: must be char, not unicode

尝试制作unicode数组也不起作用

array("u", "test")
> TypeError: must be char, not unicode

我可以制作与array兼容的unicode_literals吗?

2 个答案:

答案 0 :(得分:5)

由于array()(typecode)的第一个参数,抛出此错误。在Python 2中,这必须是非unicode字符(长度为1的字符串),而在Python 3中,这必须是unicode字符。由于这两个版本在各自的Python版本中都是str的含义,因此适用于:

array(str('u'), 'test')

答案 1 :(得分:3)

这是最近修复的阵列模块的限制(https://bugs.python.org/issue20014)。在Python 2.7.11(或更新版本)中,数组构造函数将接受strunicode作为第一个参数。

作为一种解决方法,您可以使用例如array(str("u"), "test")。我引用Dan Getz的另一个答案来解释为什么会有效。

请注意您的第一个示例使用" c" typecode仍然无法使用Python 2.7或Python 3.x.在Python 2.7上,您需要传递一个bytestring作为第二个参数(例如,通过传递b"test"作为第二个参数)。 " c"在Python 3.0中删除了typecode,所以你应该使用" b"或" B"代替。

相关问题