我正在通过Codeacademy学习Python,而他们的Madlibs练习遇到了麻烦。开始遇到麻烦后,我已经查看了演练,但是看不到它们的代码和模式之间的任何区别。这是我的代码:
STORY = "This morning % woke up feeling %. 'It is going to be a % day!' Outside, a bunch of %s were protesting to keep % in stores. They began to % to the rhythm of the %, which made all the %s very %. Concerned, % texted %, who flew % to % and dropped % in a puddle of frozen %. % woke up in the year %, in a world where %s ruled the world."
print "Let the Madlibs begin!"
name = raw_input("Enter a name: ")
print "Please provide three adjectives: "
adj_1 = raw_input("1: ")
adj_2 = raw_input("2: ")
adj_3 = raw_input("3: ")
verb = raw_input("Enter a verb: ")
print "Now, input two nouns:"
noun_1 = raw_input("1: ")
noun_2 = raw_input("2: ")
print "Please provide a word for:"
animal = raw_input("An animal: ")
food = raw_input("A food: ")
fruit = raw_input("A fruit: ")
superhero = raw_input("A superhero: ")
country = raw_input("A country: ")
dessert = raw_input("A dessert: ")
year = raw_input("A year: ")
print STORY % (name, adj_1, adj_2, animal, food, verb, noun_1, noun_2, adj_3, name, superhero, name, country, name, dessert, name, year, noun_2)
运行程序时,出现以下错误:
回溯(最近一次通话最后一次):文件“ Madlibs.py”,第34行,在 打印故事%(名称,adj_1,adj_2,动物,食物,v erb,名词_1,名词_2,adj_3,名称,超级英雄,名称,国家,名称,甜点,名称, 年,名词_2)ValueError:格式不受支持的格式字符'w'(0x77),位于 索引15
请帮助我看看我所缺少的。谢谢!
答案 0 :(得分:1)
您的格式字符串(STORY
)中包含一些无效的占位符。格式化字符串时,必须指定将在每个占位符处放置什么类型的数据。为此,您可以在%
符号后加上字母。在这种情况下,由于您总是输入字符串,因此应该为s
。因此,STORY
应该这样开始:
STORY = "This morning %s woke up feeling %s. [...]"
the Python documentation中有关于此语法的更多详细信息,它解释了如何以某种方式执行诸如格式化数字的操作。
(但是,值得注意的是,在现代Python中,我们通常使用a newer syntax using str.format()
,它看起来像这样:
STORY = "This morning {name} woke up feeling {adj_1}. [...]"
print STORY.format(name="James", adj_1="terrible")
)