一系列unicode文字

C_Z*_*_Z_ 2 python arrays unicode python-2.7

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

我正在unicode_literals__future__每个文件中导入,但是我无法使该array功能正常工作.

from array import array
from __future__ import unicode_literals
Run Code Online (Sandbox Code Playgroud)

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

array("c", "test")
> TypeError: must be char, not unicode
Run Code Online (Sandbox Code Playgroud)

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

array("u", "test")
> TypeError: must be char, not unicode
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*etz 5

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

array(str('u'), 'test')
Run Code Online (Sandbox Code Playgroud)