Python Array tounicode() 方法用于将数组转换为 unicode 字符串。要执行此方法,数组必须是 'u' 类型的数组。
语法
以下是 Python Array tounicode() 方法的语法 -
参数
此方法不接受任何参数。
返回值
此方法返回数组的 Unicode 字符串。
示例 1
以下是 Python Array tounicode() 方法的基本示例 -
输出
以下是上述代码的输出 -
Array Elements : array('u', 'abcdef')
Elements After the Conversion : abcdef
Elements After the Conversion : abcdef
示例 2
如果当前数组不是 string 数据类型,则此方法将生成 ValueError。
在这里,我们创建了一个 int 数据类型的数组,当我们尝试转换为 unicode 字符串时,我们将得到一个错误 -
输出
Array Elements : array('i', [1, 2, 3, 4, 5])
Traceback (most recent call last):
File "E:\pgms\Arraymethods prgs\tounicode.py", line 22, in <module>
arr2.tounicode()
ValueError: tounicode() may only be called on unicode type arrays
Traceback (most recent call last):
File "E:\pgms\Arraymethods prgs\tounicode.py", line 22, in <module>
arr2.tounicode()
ValueError: tounicode() may only be called on unicode type arrays
示例 3
如果数组的数据类型不是 'u' (Unicode),那么我们需要使用 tobytes() 方法将当前数组转换为字节序列,并使用 decode() 方法将数组转换为 Unicode 字符串 -
输出
以下是上述代码的输出 -
Array Elements : array('i', [12, 67, 89, 34])
Elements After the Conversion : array('i', [12, 67, 89, 34])
Elements After the Conversion : array('i', [12, 67, 89, 34])