Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python Array tounicode() Method



The Python arraytounicode() method is used to convert the array to aunicode string. To execute this method the array must be a type'u' array.

Syntax

Following is the syntax of Python arraytounicode() method −

array_name.tounicode()

Parameters

This method does not accept any parameter.

Return Value

This method returnsUnicode string of an array.

Example 1

Following is a basic example of the Python arraytounicode() method −

import array as arr#Initialize array with unicode charactersarr1 = arr.array("u", ['a','b','c','d','e','f'])print("Array Elements :",arr1)#Convert array to unicode stringunicode1= 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 aValueError.

Here, we have created an array ofint datatype when we try to convert to unicode string we will get an error −

import array as arrarr2=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 thetobytes() method and usedecode() method to convert the array to a Unicode string −

import array as arrmyArray = 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])
python_array_methods.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp