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

时间:2018-02-01 15:33:10

标签: 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)

4 个答案:

答案 0 :(得分:2)

您可以使用字符串格式

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

答案 1 :(得分:0)

您可zip blankseasyAnswerreplace相应的for blank, answer in zip(blanks, easyAnswer): easyQuiz = easyQuiz.replace(blank, answer)

zip

dictre.sub并使用answer_dict = dict(zip(blanks, easyAnswer)) result = re.sub("___\d___", lambda m: answer_dict[m.group()], easyQuiz) 进行回调:

List<Map<String, Integer>> newList = new ArrayList<>(list);

newList.replaceAll(eachMap -> {
  Map<String, Integer> map = new HashMap<>(eachMap);
  map.computeIfPresent("bar", (k,v) -> v * 2);
  return map;
});

答案 2 :(得分:0)

您可以将字符串格式设置为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'

答案 3 :(得分:0)

问题有点令人困惑,尤其是'难度'和'answerList'。假设'answerList'返回四个答案的列表。你的循环将取决于难度(问题).split()。我的预感是你的循环只迭代一次,之后索引没有得到更新,因此循环在用答案替换1时停止。