Python - 型別轉換



Python 型別轉換

從程式設計的角度來看,型別轉換是指將一個型別的物件轉換為另一個型別。在這裡,我們將學習 Python 程式設計中的型別轉換。

Python 型別轉換是一個將一種資料型別的字面量轉換為另一種資料型別的過程。Python 支援兩種型別的轉換——**隱式**和**顯式**。

在 Python 中,有不同的資料型別,例如數字、序列、對映等。可能會有這種情況,你擁有某種型別的資料,但你想以另一種形式使用它。例如,使用者輸入了一個字串,但你想將其用作數字。Python 的型別轉換機制允許你這樣做。

Python 隱式轉換

當任何語言編譯器/直譯器自動將一種型別的物件轉換為另一種型別時,這稱為自動或**隱式轉換**。Python 是一種強型別語言。它不允許在不相關的資料型別之間進行自動型別轉換。例如,字串不能轉換為任何數字型別。但是,整數可以轉換為浮點數。其他語言,如 JavaScript 是一種弱型別語言,其中整數會被強制轉換為字串以進行連線。

請注意,每種資料型別的記憶體需求不同。例如,Python 中的**整數**物件佔用 4 個位元組的記憶體,而**浮點數**物件由於其小數部分而需要 8 個位元組。因此,Python 直譯器不會自動將**浮點數**轉換為**整數**,因為這會導致資料丟失。另一方面,透過將其小數部分設定為 0,可以輕鬆地將**整數**轉換為**浮點數**。

當對**整數**和**浮點數**運算元進行任何算術運算時,會發生隱式**整數**到**浮點數**的轉換。

假設我們有一個**整數**和一個**浮點數**變數

<<< a=10   # int object
<<< b=10.5 # float object

為了執行它們的加法,整數物件 10 將被升級為 10.0。它是一個浮點數,但等同於其之前的數值。現在我們可以執行兩個浮點數的加法。

<<< c=a+b
<<< print (c)
20.5

在隱式型別轉換中,位元組大小較小的 Python 物件會被升級以匹配運算中其他物件的較大位元組大小。例如,在與浮點數物件相加之前,布林物件首先會被升級為整數,然後升級為浮點數。在下面的示例中,我們嘗試將布林物件新增到浮點數中,請注意 True 等於 1,False 等於 0。

a=True;
b=10.5;
c=a+b;

print (c);

這將產生以下結果

11.5

Python 顯式轉換

儘管自動或隱式轉換僅限於**整數**到**浮點數**的轉換,但可以使用 Python 的內建函式 int()、float() 和 str() 來執行顯式轉換,例如字串到整數。

Python int() 函式

Python 的內建**int()**函式將整數字面量轉換為整數物件,將浮點數轉換為整數,並將字串轉換為整數(如果字串本身具有有效的整數字面量表示)。

使用帶有整數物件作為引數的**int()**等效於直接宣告一個**整數**物件。

<<< a = int(10)
<<< a
10

與以下相同:

<<< a = 10
<<< a
10
<<< type(a)
<class 'int>

如果**int()**函式的引數是浮點數物件或浮點表示式,它將返回一個整數物件。例如:

<<< a = int(10.5) #converts a float object to int
<<< a
10
<<< a = int(2*3.14) #expression results float, is converted to int
<<< a
6
<<< type(a)
<class 'int'>

如果給定布林物件作為引數,**int()**函式也會返回整數 1。

<<< a=int(True)
<<< a
1
<<< type(a)
<class 'int'>

字串到整數

**int()**函式僅當字串包含有效的整數表示時,才會從字串物件返回一個整數。

<<< a = int("100")
<<< a
100
<<< type(a)
<class 'int'>
<<< a = ("10"+"01")
<<< a = int("10"+"01")
<<< a
1001
<<< type(a)
<class 'int'>

但是,如果字串包含非整數表示,Python 將引發 ValueError。

<<< a = int("10.5")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.5'
<<< a = int("Hello World")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello World'

int() 函式也可以從二進位制、八進位制和十六進位制字串返回整數。為此,函式需要一個 base 引數,該引數必須分別為 2、8 或 16。字串應具有有效的二進位制/八進位制/十六進位制表示。

二進位制字串轉換為整數

字串應該只由 1 和 0 組成,並且基數應為 2。

<<< a = int("110011", 2)
<<< a
51

二進位制數 110011 的十進位制等價值為 51。

八進位制字串轉換為整數

字串只能包含 0 到 7 的數字,並且基數應為 8。

<<< a = int("20", 8)
<<< a
16

八進位制數 20 的十進位制等價值為 16。

十六進位制字串轉換為整數

字串只能包含十六進位制符號,即 0-9 和 A、B、C、D、E 或 F。基數應為 16。

<<< a = int("2A9", 16)
<<< a
681

十六進位制數 2A9 的十進位制等價值為 681。您可以使用 Windows、Ubuntu 或智慧手機中的計算器應用程式輕鬆驗證這些轉換。

以下是如何將數字、浮點數和字串轉換為整數資料型別的示例

a = int(1)     # a will be 1
b = int(2.2)   # b will be 2
c = int("3")   # c will be 3

print (a)
print (b)
print (c)

這將產生以下結果:

1
2
3

Python float() 函式

float() 是 Python 中的內建函式。如果引數是浮點字面量、整數或具有有效浮點表示的字串,則它返回一個浮點物件。

使用浮點物件作為引數的 float() 等效於直接宣告浮點物件。

<<< a = float(9.99)
<<< a
9.99
<<< type(a)
<class 'float'>

與以下相同:

<<< a = 9.99
<<< a
9.99
<<< type(a)
<class 'float'>

如果float() 函式的引數是整數,則返回值是一個浮點數,其小數部分設定為 0。

<<< a = float(100)
<<< a
100.0
<<< type(a)
<class 'float'>

如果字串包含有效的浮點數,則float() 函式從字串返回浮點物件;否則,將引發 ValueError。

<<< a = float("9.99")
<<< a
9.99
<<< type(a)
<class 'float'>
<<< a = float("1,234.50")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '1,234.50'

這裡出現 ValueError 的原因是字串中存在逗號。

為了進行字串到浮點數的轉換,浮點數的科學計數法也被認為是有效的。

<<< a = float("1.00E4")
<<< a
10000.0
<<< type(a)
<class 'float'>
<<< a = float("1.00E-4")
<<< a
0.0001
<<< type(a)
<class 'float'>

以下是如何將數字、浮點數和字串轉換為浮點資料型別的示例

a = float(1)     # a will be 1.0
b = float(2.2)   # b will be 2.2
c = float("3.3") # c will be 3.3

print (a)
print (b)
print (c)

這將產生以下結果:

1.0
2.2
3.3

Python str() 函式

我們看到了 Python 如何從相應的字串表示中獲得整數或浮點數。str() 函式的工作方式相反。它用引號 (') 括起整數或浮點物件以返回 str 物件。str() 函式返回任何 Python 物件的字串表示。在本節中,我們將看到 Python 中str() 函式的不同示例。

str() 函式具有三個引數。第一個必需引數(或引數)是我們要獲取其字串表示的物件。其他兩個運算子 encoding 和 errors 是可選的。

我們將執行 Python 控制檯中的 str() 函式,以輕鬆驗證返回的物件是一個字串,並帶有包含的引號 (')。

整數轉換為字串

您可以按照如下方式將任何整數轉換為字串

<<< a = str(10)
<<< a
'10'
<<< type(a)
<class 'str'>

浮點數轉換為字串

str() 函式將浮點物件及其兩種表示形式(標準表示法,用小數點分隔整數和小數部分;以及科學計數法)轉換為字串物件。

<<< a=str(11.10)
<<< a
'11.1'
<<< type(a)
<class 'str'>
<<< a = str(2/5)
<<< a
'0.4'
<<< type(a)
<class 'str'>

在第二種情況下,將一個除法表示式作為引數傳遞給 str() 函式。請注意,表示式首先被求值,然後結果被轉換為字串。

使用 E 或 e 和正或負冪的科學計數法表示的浮點數將使用 str() 函式轉換為字串。

<<< a=str(10E4)
<<< a
'100000.0'
<<< type(a)
<class 'str'>
<<< a=str(1.23e-4)
<<< a
'0.000123'
<<< type(a)
<class 'str'>

當布林常量作為引數輸入時,它將用 (') 括起來,以便 True 變成 'True'。列表和元組物件也可以作為引數傳遞給 str() 函式。生成的字串是括在 (') 中的列表/元組。

<<< a=str('True')
<<< a
'True'
<<< a=str([1,2,3])
<<< a
'[1, 2, 3]'
<<< a=str((1,2,3))
<<< a
'(1, 2, 3)'
<<< a=str({1:100, 2:200, 3:300})
<<< a
'{1: 100, 2: 200, 3: 300}'

以下是如何將數字、浮點數和字串轉換為字串資料型別的示例

a = str(1)     # a will be "1"
b = str(2.2)   # b will be "2.2"
c = str("3.3") # c will be "3.3"

print (a)
print (b)
print (c)

這將產生以下結果:

1
2.2
3.3

序列型別的轉換

列表、元組和字串是 Python 的序列型別。它們是有序或索引的專案集合。

可以使用list() 函式將字串和元組轉換為列表物件。類似地,tuple() 函式將字串或列表轉換為元組。

我們將採用這三種序列型別的每個物件,並研究它們的相互轉換。

<<< a=[1,2,3,4,5]   # List Object
<<< b=(1,2,3,4,5)   # Tupple Object
<<< c="Hello"       # String Object

### list() separates each character in the string and builds the list
<<< obj=list(c)
<<< obj
['H', 'e', 'l', 'l', 'o']

### The parentheses of tuple are replaced by square brackets
<<< obj=list(b)
<<< obj
[1, 2, 3, 4, 5]

### tuple() separates each character from string and builds a tuple of characters
<<< obj=tuple(c)
<<< obj
('H', 'e', 'l', 'l', 'o')

### square brackets of list are replaced by parentheses.
<<< obj=tuple(a)
<<< obj
(1, 2, 3, 4, 5)

### str() function puts the list and tuple inside the quote symbols.
<<< obj=str(a)
<<< obj
'[1, 2, 3, 4, 5]'

<<< obj=str(b)
<<< obj
'(1, 2, 3, 4, 5)'

因此,Python 的顯式型別轉換功能允許在內建函式的幫助下將一種資料型別轉換為另一種資料型別。

資料型別轉換函式

有幾個內建函式可以執行從一種資料型別到另一種資料型別的轉換。這些函式返回一個表示已轉換值的新物件。

序號 函式及描述
1 Python int() 函式

將 x 轉換為整數。如果 x 是字串,則 base 指定基數。

2 Python long() 函式

將 x 轉換為長整數。如果 x 是字串,則 base 指定基數。

3 Python float() 函式

將 x 轉換為浮點數。

4 Python complex() 函式

建立一個複數。

5 Python str() 函式

將物件 x 轉換為字串表示。

6 Python repr() 函式

將物件 x 轉換為表示式字串。

7 Python eval() 函式

評估字串並返回一個物件。

8 Python tuple() 函式

將 s 轉換為元組。

9 Python list() 函式

將 s 轉換為列表。

10 Python set() 函式

將 s 轉換為集合。

11 Python dict() 函式

建立一個字典。d 必須是 (鍵,值) 元組的序列。

12 Python frozenset() 函式

將 s 轉換為凍結集。

13 Python chr() 函式

將整數轉換為字元。

14 Python unichr() 函式

將整數轉換為 Unicode 字元。

15 Python ord() 函式

將單個字元轉換為其整數值。

16 Python hex() 函式

將整數轉換為十六進位制字串。

17 Python oct() 函式

將整數轉換為八進位制字串。

廣告