TypeError:在字符串格式转换为color-tex的过程中,并非所有参数都被转换

2024-10-04 05:20:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想自己做一个游戏,这是我的第一个。在这本书中,我试图随着时间的推移添加一些功能,有一天我想出了一个主意,给某些关键词添加颜色。这就是我所拥有的:

print("The Text Based Game v0.1.0.0")
import time
import sys

time.sleep(1.5)
name = input("What is your name? ")
print("%s, are you a Warlock, Titan, or Hunter? Type 'list' if you would like a discription of each class." % (name))

playerclass = input()

if playerclass == ("list"):
  print ("\nWarlocks are powerful guardians. They hit hard but can't take in much in return. \n\nTitans are tanks. In the front of the line taking in bullets for others.\n\nHunters are the middle man. They are fast but besides that they don't have much else to bring to the table.\n")
  time.sleep(2)
  print ("Will you chose to be a Warlock, Titan, or Hunter?")

  playerclass = input()

现在当代码问你想成为什么职业时,我希望“术士”、“泰坦”和“猎人”这些词以不同的颜色出现。这就是我要做的:

^{pr2}$

它会引出一个错误:

Traceback (most recent call last):
  File "python", line 14, in <module>
TypeError: not all arguments converted during string formatting

我不想写”前蓝+“术士”+Style.RESET全部“每次引用时,我都希望系统可以回拨”前蓝+“术士”+Style.RESET全部“当我写术士的时候。我认为我的想法应该有效,但我执行错了。。。在

请注意,我把这些都写在里面了更换这里是python3.6.1中代码的链接更换{a1}


Tags: thetonameinimportyouinputtime
2条回答

这个问题不是因为Colorama。这里的问题是%运算符的优先级高于+,因此Python正在尝试在此处添加名称:

"? Type 'list' if you would like a discription of each class." % (name)

在它使用+组合所有这些字符串之前。简单的解决方案是将整个字符串表达式括在括号中:

^{pr2}$

输出

Bode, are you a Warlock, Titan, orHunter? Type 'list' if you would like a discription of each class.

但是,如果不手动添加字符串,而使用format方法而不是%,那么阅读起来会更容易。在

Warlock = "Warlock"
Titan = "Titan"
Hunter = "Hunter"

name = "Bode"

print("{}, are you a {}, {}. or {}?".format(name, Warlock, Titan, Hunter), end=" ")
print("Type 'list' if you would like a description of each class.")

输出

Bode, are you a Warlock, Titan. or Hunter? Type 'list' if you would like a description of each class.

您的问题是字符串格式不能跳过+串接。可通过以下方法解决:

Warlock = Fore.BLUE + "Warlock" + Style.RESET_ALL
Titan = Fore.RED + "Titan" + Style.RESET_ALL
Hunter = Fore.GREEN + "Hunter" + Style.RESET_ALL

time.sleep(1.5)
name = input("What is your name? ")
print ("%s, are you a " % (name) +Warlock+ ", " +Titan+", or" +Hunter+ "? Type 'list' if you would like a discription of each class.")

您必须在%s, are you a字符串旁边附加% (name)。我还删除了一堆不必要的括号和东西。在

相关问题 更多 >