数据类型转换
数据类型转换
在Python中只有强制类型转换,跟Java不同,Java有自动类型转换。
在 Python 中,数据类型转换(也称为类型转换)是指将一个变量从一种数据类型转换为另一种数据类型。
常见的数据类型转换函数
| 函数名 | 描述 |
|---|---|
int() |
将值转换为整数类型 |
float() |
将值转换为浮点数类型 |
str() |
将值转换为字符串类型 |
bool() |
将值转换为布尔类型(True 或 False) |
list() |
将可迭代对象转换为列表 |
tuple() |
将可迭代对象转换为元组 |
set() |
将可迭代对象转换为集合 |
dict(d) |
将键值对序列转换为字典,d必须是一个序列的元组 |
这里我不赘述,直接上代码演示即可。
Python 3.12.7 (main, Nov 8 2024, 17:55:36) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> int('3')
3
>>> int('3.14')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.14'
>>> int('Hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello'
>>> float(3.14)
3.14
>>> str(['Hello','World'])
"['Hello', 'World']"
>>> bool(0)
False
>>> bool(1)
True
>>> bool('Hello')
True
>>> bool([])
False
>>> list((1,2,3,4))
[1, 2, 3, 4]
>>> tuple([1,2,3,4])
(1, 2, 3, 4)
>>> set(['linux','c','python'])
{'linux', 'c', 'python'}
>>> dict([('name','burgess'),('age',18)])
{'name': 'burgess', 'age': 18}
>>> dict((('name','burgess'),('age',18)))
{'name': 'burgess', 'age': 18}
>>>
注意点:字典的转换格式有点奇怪,要额外注意。
浙公网安备 33010602011771号