[英]I don't know how to fix an unary +: 'str' error
I have been attempting to write a game as an exercise in learning to use Python.我一直在尝试编写一个游戏作为学习使用 Python 的练习。 I wrote a story into my code as a form of variable that is essentially a lot of other variables concatenated with strings to form the story.我在我的代码中写了一个故事作为一种变量形式,它本质上是许多其他变量与字符串连接以形成故事。 However, when I run the code I get the error:但是,当我运行代码时,我得到了错误:
TypeError: bad operand type for unary +: 'str'. TypeError:一元+的错误操作数类型:'str'。
From what research I have done this seems to happen when something like a comma is in the wrong place or both a comma and a '+' are used at the same time accidentally.根据我所做的研究,当逗号之类的位置错误或意外同时使用逗号和“+”时,似乎会发生这种情况。 I have checked my code and I don't see anything that might cause this problem.我检查了我的代码,没有看到任何可能导致此问题的内容。 Any help would be appreciated.任何帮助,将不胜感激。
My code looks like this:我的代码如下所示:
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)
A minimal example of what you're seeing:您所看到的一个最小示例:
>>> +"hello"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
>>>
The unary +
operator only works for numbers.一元+
运算符仅适用于数字。 In this case, you need to switch +name
to name
.在这种情况下,您需要将+name
切换为name
。
Or use an f-string.或者使用 f 字符串。
>>> name = "Bob"
>>> f"Hi, {name}"
'Hi, Bob'
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.