gpt4 book ai didi

python - 为什么 Python 在连接字符串时不进行类型转换?

转载 作者:IT老高 更新时间:2023-10-28 20:24:22 25 4
gpt4 key购买 nike

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

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

(错误是“TypeError: cannot concatenate 'str' and 'int' objects”)。

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

最佳答案

问题在于转换不明确,因为+既表示字符串连接,也表示数字加法。以下问题同样有效:

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

这正是不幸地困扰着 Javascript 的松散类型问题。

关于python - 为什么 Python 在连接字符串时不进行类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6380500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com