用另一个字符串替换python列表中的字符串

2024-04-25 23:59:15 发布

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

目前我的循环停止在用答案替换1。 如何循环它,使它用4个答案替换所有4个空格?你知道吗

easyQuiz = "There are ___1___ countries in the world. The countries with the biggest landmass is ___2___. The coldest continent in the world is ___3___. ___4___ is the capital of China"

blanks = ["___1___","___2___","___3___","___4___"]

easyAnswer = ["195","Russia","Antartica","Beijing"]

#asks users to choose difficulty level
question = raw_input("Shall we start? Easy, Medium, Hard?")


if question == "Easy" or question == "easy":
    answerChoice = easyAnswer

answerChoice = answerList(question)
newprompt = []
newlist = []
index = 0
maxblanks = 3

for quizwords in difficulty(question).split():

    if quizwords == "1" :
        quizwords = quizwords.replace("1",answerChoice[index])


    elif quizwords == "2" :
        quizwords = quizwords.replace("2",answerChoice[index])

        index = index + 1
    newlist.append(quizwords)
    joinedlist = " ".join(newlist)

Tags: the答案inworldindexiseasycountries
3条回答

可以使用字符串格式

def easyQuiz(vals):
      return """
There are {} countries in the world.
The countries with the biggest landmass is {}.
The coldest continent in the world is {}.
{} is the capital of China""".format(*vals)

print(easyQuiz(("___1___","___2___","___3___","___4___")))
# There are ___1___ countries in the world.
# The countries with the biggest landmass is ___2___.
# The coldest continent in the world is ___3___.
# ___4___ is the capital of China

print(easyQuiz(("195","Russia","Antartica","Beijing")))
# There are 195 countries in the world.
# The countries with the biggest landmass is Russia.
# The coldest continent in the world is Antartica.
# Beijing is the capital of China

可以将字符串格式与regex一起使用:

import re
easyQuiz = "There are ___1___ countries in the world. The countries with the biggest landmass is ___2___. The coldest continent in the world is ___3___. ___4___ is the capital of China"
easyAnswer = ["195","Russia","Antartica","Beijing"]
answers = re.sub('___\d+___', '{}', easyQuiz).format(*easyAnswer)

输出:

'There are 195 countries in the world. The countries with the biggest landmass is Russia. The coldest continent in the world is Antartica. Beijing is the capital of China'

你可以zip循环中的blanks与相应的easyAnswerreplace循环。你知道吗

for blank, answer in zip(blanks, easyAnswer):
    easyQuiz = easyQuiz.replace(blank, answer)

zipdict并将re.sub与回调一起使用:

answer_dict = dict(zip(blanks, easyAnswer))
result = re.sub("___\d___", lambda m: answer_dict[m.group()], easyQuiz)

相关问题 更多 >