【问题标题】:Madlibs program throws ValueErrorMadlibs 程序抛出 ValueError
【发布时间】:2018-11-15 00:57:31
【问题描述】:

我正在通过 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)

当我运行程序时,我收到以下错误:

Traceback(最近一次调用最后一次):文件“Madlibs.py”,第 34 行,在 print STORY % (name, adj_1, adj_2, animal, food, v erb, noun_1, noun_2, adj_3, name, superhero, name, 国家, name, 甜点, name, 年,名词_2)ValueError:不支持的格式字符'w'(0x77)在 索引 15

请帮我看看我错过了什么。谢谢!

【问题讨论】:

    标签: python-2.7


    【解决方案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")
    

    )

    【讨论】:

    • 就是这样!谢谢。不敢相信我忘记了s。干杯!
    • 太棒了!请单击旁边的复选标记接受答案。这样问题就会被标记为已解决。
    猜你喜欢
    • 2015-01-06
    • 1970-01-01
    • 2021-05-31
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2020-12-05
    • 2023-04-10
    相关资源
    最近更新 更多