簡體   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