我不知道如何修复一元+:"str"错误



我一直在尝试编写一个游戏作为学习使用Python的练习。我在我的代码中写了一个故事,作为变量的形式,它本质上是许多其他变量与字符串连接起来形成故事。然而,当我运行代码时,我得到了错误:

TypeError: unary +: 'str'的操作数类型错误。

根据我所做的研究,当逗号出现在错误的地方,或者逗号和"+"同时意外使用时,这种情况似乎就会发生。我检查了我的代码,我没有看到任何可能导致这个问题的东西。如有任何帮助,不胜感激。

我的代码是这样的:

story = (+name+ ",most doctors agree that bicycle " +verb_1+ " is a(n)) " +adj_1+
" form of exercise." +verb_2+ " a bicycle helps you develop your " +body_part+
"muscles as well as " +adverb+ " increasing the rate of your " +body_part_2+
" beat.  More " +noun+ " around the world " +verb_3+ " ride bicycles than ride "
+animal+ ".  No matter what kind of " +noun_2+ " you " +verb_4+
", always be sure to wear a(n) " +adj_2+ "helmet.  Make sure to have "
+color+ " reflectors too!")
print(story)

你所看到的一个最小的例子:

>>> +"hello"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
>>> 

一元+运算符仅适用于数字。此时需要将+name切换为name

或者使用f-string

>>> name = "Bob"
>>> f"Hi, {name}"
'Hi, Bob'
>>> 

相关内容