使用string.replace方法创建“Mad Lib”并替换多个术语

时间:2017-07-07 20:55:39

标签: python string replace

这是一个关于作业的问题,重要的部分是:“提示用户输入字符串来替换你指定的各个词性。打印出修改过的故事。[提示:字符串方法替换(旧,新的)可能会有所帮助]“

这是我到目前为止的代码:

story = "A long time ago, in a(n) PLACE-ONE far away, lived a BOY-OR-GIRL named NAME. " \
    "They lived with their mother, father, and pet ANIMAL named PET NAME. " \
    "One day, while NAME and PET NAME were playing in the PLACE-TWO, PET NAME " \
    "ran away, and NAME heard a loud SOUND and discovered that PET NAME collided " \
    "with a NOUN, and PET NAME was covered in MESSY-NOUN. As NAME went to go help PET NAME, " \
    "They too became covered in MESSY-NOUN. So they both had to ACTIVE-VERB back to PLACE-ONE and bathe in LIQUID " \
    "to get all clean. The End."
print(story)

place1 = str(input("Enter a place: "))
boyGirl = str(input("Enter a gender (can be a boy or girl): "))
bgName = str(input("Enter a name for your boy or girl: "))
animal = str(input("Enter an animal: "))
animalName = str(input("Enter a name for the animal: "))
place2 = str(input("Enter another place: "))
sound = str(input("Enter a sound: "))
noun1 = str(input("Enter a noun, preferably a large one: "))
messyNoun = str(input("Enter a noun that is messy/dirty: "))
activeVerb = str(input("Enter an action verb: "))
liquid = str(input("Enter a liquid: "))

print(story.replace("PLACE-ONE", place1))
print(story.replace("BOY-OR-GIRL", boyGirl))
print(story.replace("NAME", bgName))
print(story.replace("ANIMAL", animal))
print(story.replace("PET NAME", animalName))
print(story.replace("PLACE-TWO", place2))
print(story.replace("SOUND", sound))
print(story.replace("NOUN", noun1))
print(story.replace("MESSY-NOUN", messyNoun))
print(story.replace("ACTIVE-VERB", activeVerb))
print(story.replace("LIQUID", liquid))

我是否需要循环来替换字符串中的所有内容? 当我运行它时,它取代了那个术语而不是它,所以我只有一堆故事副本,每个副本只有一个术语被替换。或者我是否需要创建一个功能来进行替换?

2 个答案:

答案 0 :(得分:3)

story.replace()返回一个新字符串,它不会更改原始字符串。因此,每当您调用它时,您都会从原始文件开始,从上一行中删除替换项。您需要将结果重新分配回story

story = story.replace("PLACE-ONE", place1)
story = story.replace("BOY-OR-GIRL", boyGirl)
story = story.replace("NAME", bgName)
story = story.replace("ANIMAL", animal)
story = story.replace("PET NAME", animalName)
story = story.replace("PLACE-TWO", place2)
story = story.replace("SOUND", sound)
story = story.replace("NOUN", noun1)
story = story.replace("MESSY-NOUN", messyNoun)
story = story.replace("ACTIVE-VERB", activeVerb)
story = story.replace("LIQUID", liquid)
print(story)

答案 1 :(得分:1)

你真的不需要循环,@ Barmar的回答是完全足够的,但如果你不喜欢打字(比如我)或者想缩短时间,这也可能有所帮助:

keywords = ["PLACE-ONE","BOY-OR-GIRL","NAME","ANIMAL","PET NAME","PLACE-TWO","SOUND","NOUN","MESSY-NOUN","ACTIVE-VERB","LIQUID"]
replacements = [place1,boyGirl,bgName,animal,animalName,place2,sound,noun1,messyNoun,activeVerb,liquid]


for key,repl in zip(keywords,replacements):
    story = story.replace(key, repl)

希望这在某种程度上有所帮助。