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

Python 类型转换和类型转换

Python 类型转换和类型转换

在本文中,您将了解类型转换和类型转换的使用。

在学习 Python 中的类型转换之前,您应该了解 Python 数据类型。


类型转换

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

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

隐式类型转换

在隐式类型转换中,Python 自动将一种数据类型转换为另一种数据类型。此过程不需要任何用户参与。

我们来看一个例子,Python 促进低数据类型(整数)到高数据类型(浮点数)的转换,避免数据丢失。

示例一:整数转浮点数

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# 类型转换
  2. Python 关键字和标识符
  3. Python 语句、缩进和注释
  4. Python 变量、常量和文字
  5. Python 数据类型
  6. Python 输入、输出和导入
  7. Python 全局、局部和非局部变量
  8. Python 数字、类型转换和数学
  9. Python 目录和文件管理
  10. Python 错误和内置异常
  11. Java 类型转换
  12. Python 中的 type() 和 isinstance() 示例