天天看点

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'           

文章创作不易,如果您喜欢这篇文章,请关注、点赞并分享给朋友。如有意见和建议,请在评论中反馈!