亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

精通Python类型转换与强制转换:综合指南

Python类型转换与强制转换

本文讲解类型转换及其用法。

学习Python类型转换前,应了解Python数据类型。


类型转换

将一种数据类型(整数、字符串、浮点数等)的值转换为另一种数据类型的过程称为类型转换。Python有两种类型转换。

  1. 隐式类型转换
  2. 显式类型转换

隐式类型转换

隐式类型转换中,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'>

程序中:


现在尝试字符串与整数相加,看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'

程序中:


显式类型转换

显式类型转换中,用户将对象数据类型转为所需类型。使用预定义函数 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'>

程序中:


关键点回顾

  1. 类型转换是对象从一种数据类型到另一种的转换。
  2. 隐式类型转换由Python解释器自动执行。
  3. 隐式转换中Python避免数据丢失。
  4. 显式类型转换也称类型强制转换,用户用预定义函数转换对象数据类型。
  5. 强制转换中可能因强制指定类型而丢失数据。

Python

  1. 掌握 C# 类型转换:隐式、显式、Parse 与 Convert 全方位指南
  2. Python关键字与标识符:掌握保留字与命名规范
  3. Python语句、缩进与注释:清晰指南
  4. Python变量、常量与字面量完全指南
  5. 精通Python数据类型:实战指南
  6. 精通Python输入输出与模块导入:实战指南
  7. 理解Python全局、局部与非局部变量
  8. 精通 Python 数字、类型转换与数学运算
  9. 精通 Python 目录与文件操作
  10. 精通 Python 错误与内置异常
  11. 理解 Python type() 与 isinstance():实战示例详解
  12. 掌握 Java 类型转换:从自动拓宽到强制收窄及更多