python 为什么“lala”+ int需要转换为str,而“lala”* 2不需要?

xvw2m8pv  于 2023-04-04  发布在  Python
关注(0)|答案(1)|浏览(92)

此问题在此处已有答案

How can I concatenate str and int objects?(1个答案)
两年前关闭了。
这是可行的

In [2]:
"I said " + ("Hey " * 2) + "Hey!"
Out[2]:
'I said Hey Hey Hey!'

但这个不一样为什么

In [3]:
"The correct answer to this multiple choice exercise is answer number " + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    "The correct answer to this multiple choice exercise is answer number " + 2
TypeError: must be str, not int
mum43rcc

mum43rcc1#

可以用一个整数 * 乘 * 一个字符串--结果是该字符串的N次重复。
我不同意把一个字符串加到一个整数上。设计Python的人认为这是不允许的。
这就是Python的工作方式。

相关问题