Python中的数据类型转换函数总结
Python中的数据类型转换函数有以下几种:
1. int()函数
int()函数可以将其他数据类型转换为整型(int)。例如:
a = '123'
b = int(a)
print(type(b), b)
输出结果为:<class 'int'> 123
2. float()函数
float()函数可以将其他数据类型转换为浮点型(float)。例如:
a = '1.23'
b = float(a)
print(type(b), b)
输出结果为:<class 'float'> 1.23
3. str()函数
str()函数可以将其他数据类型转换为字符串型(str)。例如:
a = 123
b = str(a)
print(type(b), b)
输出结果为:<class 'str'> 123
4. list()函数
list()函数可以将其他数据类型转换为列表(list)。例如:
a = (1, 2, 3)
b = list(a)
print(type(b), b)
输出结果为:<class 'list'> [1, 2, 3]
5. tuple()函数
tuple()函数可以将其他数据类型转换为元组(tuple)。例如:
a = [1, 2, 3]
b = tuple(a)
print(type(b), b)
输出结果为:<class 'tuple'> (1, 2, 3)
6. set()函数
set()函数可以将其他数据类型转换为集合(set)。例如:
a = [1, 2, 3]
b = set(a)
print(type(b), b)
输出结果为:<class 'set'> {1, 2, 3}
7. bool()函数
bool()函数可以将其他数据类型转换为布尔型(bool)。例如:
a = 'hello'
b = bool(a)
print(type(b), b)
输出结果为:<class 'bool'> True
8. chr()函数
chr()函数可以将一个十进制整数转换为对应的ASCII码字符。例如:
a = 101
b = chr(a)
print(type(b), b)
输出结果为:<class 'str'> e
9. ord()函数
ord()函数可以将一个ASCII码字符转换为对应的十进制整数。例如:
a = 'e'
b = ord(a)
print(type(b), b)
输出结果为:<class 'int'> 101
以上就是Python中常用的数据类型转换函数介绍。在实际编程过程中,根据需求选择合适的数据类型转换函数可以提高编程效率和程序执行效率。
