Python Array tounicode() Method
The Python array tounicode() method is used to convert the array to a unicode string. To execute this method the array must be a type 'u' array.
Syntax
Following is the syntax of Python array tounicode() method −
array_name.tounicode()
Parameters
This method does not accept any parameter.
Return Value
This method returns Unicode string of an array.
Example 1
Following is a basic example of the Python array tounicode() method −
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)
Output
Following is the output of above code −
Array Elements : array('u', 'abcdef')
Elements After the Conversion : abcdef
Example 2
If the current array is not of string datatype this method will generate a ValueError.
Here, we have created an array of int datatype when we try to convert to unicode string we will get an error −
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)
Output
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
Example 3
If the datatype of array is other than 'u' (Unicode) then we need to convert the current array to a sequence of bytes using the tobytes() method and use decode() method to convert the array to a Unicode string −
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)
Output
Following is the output of the above code −
Array Elements : array('i', [12, 67, 89, 34])
Elements After the Conversion : array('i', [12, 67, 89, 34])