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”最初是 int 型別,但變數“b”是 float 型別。在執行加法運算並將結果儲存到變數“a”中後,“a”的資料型別會自動更改為 float 型別。這就是 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 提供了許多內建函式用於顯式型別轉換。

注意 - 透過顯式型別轉換將給定值強制轉換為較小的資料型別可能會導致資料丟失。例如,將 float 值轉換為 int 時,輸出結果會舍入小數位。

語法

以下是顯式型別轉換的語法 -

(required data type)(expression)

示例

以下是一個顯式型別轉換的示例 -

a = 47 b = "51" result1 = a + b b = int(b) result2 = a + b print(result2)

輸出

變數“a”的資料型別是數字,變數“b”是字串。如果將這兩個值相加並將結果儲存在 result1 變數中,則會發生 TypeError,如輸出所示。

因此,為了完成此過程,我們需要使用顯式型別轉換。“b”轉換為 int 型別後,“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(變數,基數),其中“變數”指的是字串,“基數”指定當資料型別為字串時字串所在的基數。

示例

以下是一個 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 時,只能宣告一個空浮點數資料型別變數。

示例

以下是一個 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 (引數)。

示例

以下是一個 hex 資料型別的示例 -

x = 87 y = hex(x) print(y, "is of the type", type(y))

輸出

以下是上述程式碼的輸出 -

0x57 is of the type <class 'str'>

Oct()

使用此函式將整數轉換為八進位制。此函式僅接受整數資料型別作為引數,並返回八進位制值。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”)。元組是指一組不可更改的有序值(即不可變的)。

示例

以下是一個 tuple 資料型別的示例

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,依此類推} 表示一個集合。

示例

以下是一個 set 資料型別的示例

x = 'TutorialsPoint' print(set(x))

輸出

以下是上述程式碼的輸出 -

{'r', 'a', 'i', 'o', 's', 'n', 't', 'u', 'T', 'l', 'P'}

List()

此函式透過將任何資料型別轉換為列表型別來建立列表物件。列表是可更改的且有序的。list() 的語法為list(引數),列表用 [‘one’,2,‘three’] 表示。引數可以是序列(字串、元組)、集合(集合、字典)或迭代器物件,它是可選的。

示例

以下是一個 list 資料型別的示例 -

x = 'TutorialsPoint' print(list(x))

輸出

以下是上述程式碼的輸出

['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'P', 'o', 'i', 'n', 't']

Str()

它用於將整數轉換為字串。當將不同資料型別的值與字串資料型別的值組合時,通常使用此函式。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(引數),其中引數是可選引數。如果未提供引數,它將建立一個空字典物件;如果提供了引數,它將引數轉換為字典格式。

示例

以下是一個 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'>

更新於: 2022-11-14

660 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告