为什么Python在连接字符串时不进行类型转换? [英] Why does Python not perform type conversion when concatenating strings?

查看:40
本文介绍了为什么Python在连接字符串时不进行类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,以下代码会产生错误:

In Python, the following code produces an error:

a = 'abc'
b = 1
print(a + b)

(错误是类型错误:无法连接 'str' 和 'int' 对象").

(The error is "TypeError: cannot concatenate 'str' and 'int' objects").

为什么 Python 解释器在遇到这些类型的串联时不会自动尝试使用 str() 函数?

Why does the Python interpreter not automatically try using the str() function when it encounters concatenation of these types?

推荐答案

问题是转换有歧义,因为+同时表示字符串连接数字加法.以下问题同样有效:

The problem is that the conversion is ambiguous, because + means both string concatenation and numeric addition. The following question would be equally valid:

为什么 Python 解释器在遇到这些类型的加法时不会自动尝试使用 int() 函数?

Why does the Python interpreter not automatically try using the int() function when it encounters addition of these types?

不幸的是,这正是困扰 Javascript 的松散类型问题.

This is exactly the loose-typing problem that unfortunately afflicts Javascript.

这篇关于为什么Python在连接字符串时不进行类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆