Python Array tounicode() 方法用于将数组转换为 unicode 字符串。要执行此方法,数组必须是 'u' 类型的数组。
语法
以下是 Python Array tounicode() 方法的语法 -
array_name.tounicode()
参数
此方法不接受任何参数。
返回值
此方法返回数组的 Unicode 字符串。
示例 1
以下是 Python Array tounicode() 方法的基本示例 -
import array as arr
#Initialize array with unicode characters
arr1 = arr.array("u", ['a','b','c','d','e','f'])
print("Array Elements :",arr1)
#Convert array to unicode string
unicode1= arr1.tounicode()
print("Elements After the Conversion :",unicode1)
输出
以下是上述代码的输出 -
Array Elements : array('u', 'abcdef')
Elements After the Conversion : abcdef
Elements After the Conversion : abcdef
示例 2
如果当前数组不是 string 数据类型,则此方法将生成 ValueError。
在这里,我们创建了一个 int 数据类型的数组,当我们尝试转换为 unicode 字符串时,我们将得到一个错误 -
import array as arr
arr2=arr.array("i",[1,2,3,4,5])
print("Array Elements :",arr2)
arr2.tounicode()
print("Elements After the Conversion :",arr2)
输出
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 字符串 -
import array as arr
myArray = arr.array('i',[12,67,89,34])
print("Array Elements :",myArray)
myArray.tobytes().decode()
print("Elements After the Conversion :",myArray)
输出
以下是上述代码的输出 -
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])