Menu Close

Python 类型转换和强制类型转换

1.类型转换

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

  • 隐式类型转换
  • 显式类型转换

2.隐式类型转换

在隐式类型转换中,Python 自动将一种数据类型转换为另一种数据类型。此过程不需要程序给出明确指令。

让我们看一个示例,其中 Python 促进将较低数据类型(整数)转换为较高数据类型(浮点数)以避免数据丢失。

例2.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'>

Process finished with exit code 0

在上述程序中,

  • 整型变量 num_int 和浮点变量 num_flo相加,将值存储在 num_new 中;
  • 程序分别查看所有三个对象的数据类型;
  • 在输出中,我们可以看到 num_int 的数据类型是整数,而 num_flo 的数据类型是浮点数;
  • 输出结果可以看到 num_new 具有浮点数据类型,因为 Python 总是将较小的数据类型转换为较大的数据类型,以避免数据丢失。

将一个字符串和一个整数相加,查看 Python 是如何处理的。

例2.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)

结果

在上述程序中,

  • 两个变量 num_int (整型)和 num_str (字符串)相加。
  • 从输出中可以看出,我们得到了 TypeError。 Python 在这种情况下无法使用隐式转换。
  • 但是,Python 为这些类型的情况提供了一种解决方案,称为显式转换。

3.显式类型转换

在显式类型转换中,用户将对象的数据类型转换为所需的数据类型。我们使用 int()、float()、str() 等预定义函数来执行显式类型转换。

这种类型的转换也称为强制类型转换(Type Casting,类型铸造),因为用户转换(更改)对象的数据类型。

语法

<required_datatype>(expression)

强制类型转换可以通过将所需的数据类型函数分配给表达式来完成。

示例3.1:使用显式转换将字符串和整数相加

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'>

Process finished with exit code 0

在上述程序中,

  • 两个变量 num_str (字符串型)和 num_int (整数型)相加。
  • 我们使用 int() 函数将 num_str 从 字符串(高)转换为 整数型(低) 类型以执行加法。
  • 将 num_str 转换为整数值后,Python 可以将这两个变量相加。
  • 程序自动将 num_sum 数据类型设为整数。

关键点

  • 类型转换是将对象从一种数据类型转换为另一种数据类型。
  • 隐式类型转换由 Python 解释器自动执行。
  • Python 避免了隐式类型转换中的数据丢失。
  • 显式类型转换也称为强制类型转换,对象的数据类型由用户使用预定义的函数进行转换。
  • 在类型铸造(强制类型转换)中,当我们将对象强制为特定数据类型时,可能会发生数据丢失。

wer

除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Leave the field below empty!

Posted in Python教程

Related Posts