Python 陣列 tounicode() 方法



Python 陣列的 tounicode() 方法用於將陣列轉換為 Unicode 字串。要執行此方法,陣列必須是型別 'u' 陣列。

語法

以下是 Python 陣列 tounicode() 方法的語法:

array_name.tounicode()

引數

此方法不接受任何引數。

返回值

此方法返回陣列的 Unicode 字串

示例 1

以下是 Python 陣列 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

示例 2

如果當前陣列不是字串資料型別,則此方法將生成 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

示例 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])
python_array_methods.htm
廣告