Python 中有哪些不同的資料轉換方法?
型別轉換是指將 Python 資料型別轉換為另一種資料型別的過程。Python 中型別轉換的基本類別包括隱式型別轉換和顯式型別轉換。
本文將涵蓋以下主題:
Python 中的**隱式型別轉換**是由 Python 直譯器自動執行的。
在 Python 中,**顯式型別轉換**必須由程式設計師直接執行。
讓我們深入研究這兩種方法,並結合一些示例進行講解。
隱式型別轉換
隱式型別轉換是指 Python 直譯器在沒有程式設計師干預的情況下自動更改物件資料型別。為了避免執行時資料丟失,較小的資料型別會被轉換為較大的資料型別。
我們不需要在程式碼中顯式使用任何函式,因為轉換會自動發生。
**注意** - 直譯器將高階語言轉換為計算機可理解的語言。直譯器逐行讀取程式碼,然後直接執行。
示例
以下是隱式型別轉換的示例
a = 13 print("The Data Type of Variable a is:",type(a)) b = 6.9 print("The Data Type of Variable b is:",type(b)) a = a - b print("\nThe value of a now is:",a) print("*Updated Data Type of the Variable a is:",type(a))
輸出
從上面的示例可以看出,變數“a”最初是整數型別,但變數“b”是浮點數型別。在求和過程之後並將結果儲存到變數“a”中, “a”的資料型別會自動更改為浮點數型別。這就是 Python 程式語言中的隱式型別轉換。
The Data Type of Variable a is: <class 'int'> The Data Type of Variable b is: <class 'float'> The value of a now is: 6.1 *Updated Data Type of the Variable a is: <class 'float'>
**注意** - `type()` 方法返回輸入引數的類型別。因此,`type(9)` 返回類“int”的物件,而 `type("9")` 返回類“string”的物件。
顯式型別轉換
使用者將物件的型別更改為顯式型別轉換所需的資料型別。顯式型別轉換使用預定義函式(如 `int()`、`float()` 和 `str()`)來完成。
此轉換過程也稱為**型別強制轉換**,因為它涉及使用者更改物件的型別。
當程式設計師明確且精確地指定程式時,就會進行顯式型別轉換。Python 提供了一些內建函式用於顯式型別轉換。
**注意** - 透過顯式型別轉換將給定值強制轉換為較小的資料型別可能會導致資料丟失。例如,將浮點數轉換為整數時,會對輸出中的小數位進行四捨五入。
語法
以下是顯式型別轉換的語法:
(required data type)(expression)
示例
以下是顯式型別轉換的示例:
a = 47 b = "51" result1 = a + b b = int(b) result2 = a + b print(result2)
輸出
變數“a”的資料型別是數字,“b”是字串。如果將這兩個值相加並將結果儲存到 `result1` 變數中,則會發生 `TypeError`,如輸出所示。
因此,為了完成此過程,我們必須使用顯式型別轉換。“b”轉換為整數後,“a”和“b”相加。輸出顯示 400,該值儲存在 `result2` 變數中。
Traceback (most recent call last): File "main.py", line 3, in <module> result1 = a + b TypeError: unsupported operand type(s) for +: 'int' and 'str'
讓我們用一個簡單的示例來說明 Python 提供的每種顯式轉換函式型別。
`int()`
此函式可以將任何資料型別轉換為整數資料型別。`int()` 函式需要 2 個引數,其語法為 `int(變數, 基數)`,其中“變數”指的是字串,“基數”指定字串所在的基數(當資料型別為字串時)。
示例
以下是整數資料型別的示例:
a = "58" print("Before conversion the data type of variable a is:",type(a)) number = int(a) print("\nAfter conversion the data type of variable a is:",type(number))
輸出
以下是上述程式碼的輸出:
Before conversion the data type of variable a is: <class 'str'> After conversion the data type of variable a is: <class 'int'>
`float()`
此函式可以將任何資料型別轉換為浮點型別。`float()` 的語法為 `float(引數)`,其中引數是可選引數。使用 `float()` 函式且不帶引數時,只能宣告一個空浮點數型別變數。
示例
以下是浮點數型別的示例:
a = "84" print("Before conversion the data type of variable a is : %s and a value : %s "%(type(a),a)) number = float(a) print("\nAfter conversion the data type of variable a is: %s and number value : %s "%(type(number),number))
輸出
以下是上述程式碼的輸出:
Before conversion the data type of variable a is : <class 'str'> and a value : 84 After conversion the data type of variable a is: <class 'float'> and number value : 84.0
`ord()`
使用此函式,可以將字元轉換為整數。此函式接受單個字元引數 `ord(字元)`,並將其轉換為其對應的 Unicode 程式碼值。可以使用此函式來確定字串是否包含特殊字元(如表情符號)。此函式只能使用一個字元。
示例
以下是 `ord()` 資料型別的示例:
char = "H" unicode_character = ord(char) print("\nThe Unicode of the character %s is %s "%(char,unicode_character))
輸出
以下是上述程式碼的輸出
The Unicode of the character H is 72
`hex()`
使用此函式將數字轉換為十六進位制。此函式接受單個整數或浮點數引數,其返回值為十六進位制。`hex()` 函式的語法為 `hex(引數)`。
示例
以下是十六進位制資料型別的示例:
x = 87 y = hex(x) print(y, "is of the type", type(y))
輸出
以下是上述程式碼的輸出:
0x57 is of the type <class 'str'>
`oct()`
使用此函式將整數轉換為八進位制。此函式僅接受整數資料型別作為引數,其返回值為八進位制值。`oct()` 函式的語法為 `oct(引數)`。
示例
以下是八進位制資料型別的示例:
x = 38 y = oct(x) print(y, "is of the type", type(y))
輸出
以下是上述程式碼的輸出:
0o46 is of the type <class 'str'>
`tuple()`
此函式用於根據值建立元組。元組可以將多個專案儲存在一個變數中。`tuple()` 方法的語法為 `tuple(引數)`,元組的元素為 (“one”,“two”,“three”)。元組是一組不可變的有序值(即不可變)。
示例
以下是元組資料型別的示例
x = 'TutorialsPoint' print(tuple(x))
輸出
以下是上述程式碼的輸出:
('T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'P', 'o', 'i', 'n', 't')
`set()`
轉換為集合後,此函式返回型別。其語法為 `set(可迭代物件)`;不需要提供引數。集合是無序的。{值 1,值 2,值 3,值 4,等等} 表示一個集合。
示例
以下是集合資料型別的示例
x = 'TutorialsPoint' print(set(x))
輸出
以下是上述程式碼的輸出:
{'r', 'a', 'i', 'o', 's', 'n', 't', 'u', 'T', 'l', 'P'}
`list()`
此函式透過將任何資料型別轉換為列表型別來建立列表物件。列表是可變且有序的。`list()` 的語法為 `list(引數)`,列表用 [‘one’,2,‘three’] 表示。引數可以是序列(字串、元組)、集合(集合、字典)或迭代器物件,它是可選的。
示例
以下是列表資料型別的示例:
x = 'TutorialsPoint' print(list(x))
輸出
以下是上述程式碼的輸出
['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'P', 'o', 'i', 'n', 't']
`str()`
它用於將整數轉換為字串。當將不同資料型別的數值與字串資料型別的數值組合時,通常使用此函式。`str()` 函式的語法為 `str(引數)`。
示例
以下是字串資料型別的示例:
x = 39 y = 489.28 z = complex(39,4) print(str(x)) print(str(y)) print(str(z))
輸出
以下是上述程式碼的輸出:
39 489.28 (39+4j)
`dict()`
此方法使用有序的 (鍵,值) 值元組建立字典。字典由建構函式 `dict()` 建立。這意味著如果未提供引數,則建立空字典。其語法為 `dict(引數)`,其中引數是可選引數。如果未提供引數,則建立空字典物件;如果提供了引數,則將其轉換為字典格式。
示例
以下是字典資料型別的示例:
x = (('s', 6), ('a', 3), ('r', 5), ('i', 8), ('k', 1)) print(dict(x))
輸出
以下是上述程式碼的輸出:
{'s': 6, 'a': 3, 'r': 5, 'i': 8, 'k': 1}
`chr()`
此函式將數字轉換為其 ASCII 字元等效項。`chr()` 函式的語法為 `chr(數字)`,需要一個整數。此外,如果傳遞超出範圍的整數,則該方法將返回 `ValueError`。
示例
以下是 `chr()` 資料型別的示例:
x = 437 y = 57 print(chr(x), "type is", type(chr(x))) print(chr(y), "type is", type(chr(y)))
輸出
以下是上述程式碼的輸出:
Ƶ type is <class 'str'> 9 type is <class 'str'>