繁体   English   中英

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

[英]I don't know how to fix an unary +: 'str' error

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

TypeError:一元+的错误操作数类型:'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 字符串。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM