天天看點

Python 中的資料類型轉換

作者:資訊科技雲課堂
Python 中的資料類型轉換

将一種 Python 資料類型轉換為另一種資料類型的過程稱為類型轉換。當需要確定資料與特定函數或操作相容時,可能需要進行類型轉換。

Python 中的資料類型轉換

如何在 Python 中進行類型轉換

Python 提供了四個可用于類型轉換的内置函數。這些函數是:str()、int()、float()、bool()。這些函數分别傳回字元串、整數、浮點數或布爾值。

需要注意一點是,并非所有值都可以強制轉換為其他資料類型。例如,如果嘗試将不表示數字的字元串轉換為整數或浮點數,将傳回 ValueError。

>>> n = 'a123'
>>> int(n)
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a123'           

将整數類型轉換為字元串

要将整數轉換為字元串,可以使用 str() 函數。

>>> x=123
>>> str(x)
'123'           

如果要将數值與字元串連接配接,則必須将其轉換為字元串,否則将傳回 TypeError :

>>> x=123
>>> y="abc"
>>> x+y
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'           

正确方法:

>>> x=123
>>> y="abc"
>>> str(x)+y
'123abc'           

将整數轉換為浮點數

将整數轉換為浮點數,可以使用 float() 函數

>>> x=123
>>> float(x)
123.0           

将浮點數轉換為整數

要将浮點數轉換為整數,可以使用 int() 函數。

>>> x=123.4
>>> int(123.4)
123
>>> int(123.9)
123           

特别注意,浮點數轉換為整數是向下取整,不是四舍五入。

将浮點數轉換為字元串

>>> x=123.4
>>> str(x)
'123.4'           

将字元串轉換為整數

>>> x='123'
>>> int(x)
123
>>> x='123.4'
>>> int(x)
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123.4'           

要将字元串轉為整數,需要字元串是能夠表示整數的字元串,字元串中不能含有數字之外的其他字元。

将字元串轉換為浮點數

将字元串轉換為浮點數,使用 float() 函數。

>>> x='123.4'
>>> float(x)
123.4
>>> x='a123.4'
>>> float(x)
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
ValueError: could not convert string to float: 'a123.4'           

同樣,要将字元串轉為浮點數,需要字元串是能夠表示浮點數的字元串,字元串隻能含有數字和小數點。

将其它類型轉換為布爾值

将參數轉換為布爾值,使用 bool() 函數。

>>> bool()
False
>>> bool(0)
False
>>> bool(1)
True
>>> bool(1.2)
True
>>> bool(-1)
True
>>> bool(-1.1)
True
>>> bool("a")
True           

bool() 函數的參數是“0”或省略,傳回 False,否則,傳回 True。

将布爾值轉換為其它類型

>>> int(True)
1
>>> int(False)
0
>>> float(True)
1.0
>>> float(False)
0.0
>>> str(True)
'True'
>>> str(False)
'False'           

文章創作不易,如果您喜歡這篇文章,請關注、點贊并分享給朋友。如有意見和建議,請在評論中回報!