【发布时间】:2023-04-11 11:29:01
【问题描述】:
大量文献证明,str 需要将 int 转换为字符串,然后才能连接它们:
'I am ' + str(n) + ' years old.'
Python 不允许这样做一定有一个根本原因
'I am ' + n + ' years old.'
我想知道这个原因是什么。在我的项目中,我打印了很多数字并最终得到这样的代码。
'The GCD of the numbers ' + str(a) + ', ' + str(b) + ' and ' + str(c) + ' is ' + str(ans) + '.'
如果我能去掉'str'会更漂亮。这就是让我的经历特别令人烦恼的原因。我正在使用 SymPy,所以我有这样的代码:
'Consider the polynomial ' + (a*x**2 + b*x + c)
这在 99% 的时间都有效,因为我们为 SymPy 表达式和字符串重载了“+”。但是对于整数我们不能这样做,因此,当 a=b=0 并且多项式减少为整数常量时,此代码将失败!所以对于那个异常情况,我不得不写:
'Consider the polynomial ' + str(a*x**2 + b*x + c)
同样,'string' + str(int) 的解决方案很简单,但我的帖子的目的是理解 Python 不允许 'string' + int 的方式,例如,Java 允许。
【问题讨论】:
-
因为显式优于隐式;连接需要显式转换,对象通常不会被隐式强制转换。
-
你真的应该了解
str.format():'The GCD of the numbers {}, {} and {} is {}.'.format(a, b, c, ans)。 Python 3.6 及更高版本提供f字符串:f'The GCD of the numbers {a}, {b} and {c} is {ans}.' -
@MartijnPieters 奇怪,但你可以对 print("I am ", n, " years old.") 做同样的事情,而且没有人会因为某种原因抱怨隐式转换。所以用逗号替换“+”运算符突然就可以了?
-
@BulgarSadykov
print()显式使用str()、as documented将所有参数转换为字符串:所有非关键字参数都转换为@987654335之类的字符串@ 会。print()有一个明确的、狭窄的用例,+运算符有一个更广泛的用例,远远超出了字符串。
标签: python string int operator-overloading concatenation