为什么 Python 不能在不转换的情况下将整数和字符串打印在一起?


num = 4
print(num + " other words")

在此代码中,Python 会返回一个错误,即它无法像这样将整数和字符串打印在一起 - 我知道可以使用 str 将 int 转换为字符串,但为什么 Python 不自动执行此操作?

由Programiz编写

类型转换 将一种数据类型(整数、字符串、浮点数等(的值转换为另一种数据类型的过程称为类型转换。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'>

在上面的程序中,

我们添加两个变量num_int和num_flo,将值存储在num_new中。 我们将分别查看所有三个对象的数据类型。 在输出中,我们可以看到 num_int 的数据类型是整数,而 num_flo 的数据类型是浮点数。 此外,我们可以看到num_new具有浮点数据类型,因为 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从字符串(更高(转换为整数(较低(类型来执行加法。 将num_str转换为整数值后,Python 能够添加这两个变量。 我们得到num_sum值和数据类型为整数。

它可以:

num = 4
print(f"{num} other words")

最新更新