精通Python类型转换与强制转换:综合指南
Python类型转换与强制转换
本文讲解类型转换及其用法。
学习Python类型转换前,应了解Python数据类型。
类型转换
将一种数据类型(整数、字符串、浮点数等)的值转换为另一种数据类型的过程称为类型转换。Python有两种类型转换。
- 隐式类型转换
- 显式类型转换
隐式类型转换
隐式类型转换中,Python自动将一种数据类型转换为另一种,无需用户干预。
看示例:Python将较低类型(整数)提升为较高类型(浮点数)以避免数据丢失。
示例 1:整数转浮点数
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:", type(num_int))
print("datatype of num_flo:", type(num_flo))
print("Value of num_new:", num_new)
print("datatype of num_new:", type(num_new))
运行输出:
datatype of num_int: <class 'int'> datatype of num_flo: <class 'float'> Value of num_new: 124.23 datatype of num_new: <class 'float'>
程序中:
- 将 num_int 和 num_flo 相加,结果存 num_new。
- 查看三对象数据类型。
- 输出显示 num_int 为
integer,num_flo 为float。 - num_new 为
float,因Python总将较小类型转较大类型以避免数据丢失。
现在尝试字符串与整数相加,看Python如何处理。
示例 2:字符串(较高)与整数(较低)相加
num_int = 123
num_str = "456"
print("Data type of num_int:", type(num_int))
print("Data type of num_str:", type(num_str))
print(num_int + num_str)
运行输出:
Data type of num_int: <class 'int'> Data type of num_str: <class 'str'> Traceback (most recent call last): File "python", line 7, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'
程序中:
- 相加 num_int 和 num_str。
- 输出显示
TypeError。Python无法在此隐式转换。 - Python提供显式转换解决此类情况。
显式类型转换
显式类型转换中,用户将对象数据类型转为所需类型。使用预定义函数 int()、float()、str() 等执行显式转换。
此类转换也称类型强制转换,因用户强制转换对象数据类型。
语法:
<required_datatype>(expression)
通过将所需数据类型函数赋给表达式实现强制转换。
示例 3:显式转换实现字符串与整数相加
num_int = 123
num_str = "456"
print("Data type of num_int:", type(num_int))
print("Data type of num_str before Type Casting:", type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:", type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:", num_sum)
print("Data type of the sum:", type(num_sum))
运行输出:
Data type of num_int: <class 'int'> Data type of num_str before Type Casting: <class 'str'> Data type of num_str after Type Casting: <class 'int'> Sum of num_int and num_str: 579 Data type of the sum: <class 'int'>
程序中:
- 相加 num_str 和 num_int。
- 用
int()将 num_str 从字符串(较高)转整数(较低)以执行加法。 - 转换后Python能相加两变量。
- 得到 num_sum 值及类型为整数。
关键点回顾
- 类型转换是对象从一种数据类型到另一种的转换。
- 隐式类型转换由Python解释器自动执行。
- 隐式转换中Python避免数据丢失。
- 显式类型转换也称类型强制转换,用户用预定义函数转换对象数据类型。
- 强制转换中可能因强制指定类型而丢失数据。
Python