gpt4 book ai didi

python - 将某些内容添加到字符串后,如何打印修改以及字符串的其余部分?

转载 作者:行者123 更新时间:2023-12-01 02:39:11 25 4
gpt4 key购买 nike

所以这个标题可能没有意义。但这里是代码:

def play_game(ml_string, blanks, selectedLevel):


replaced = []
ml_string = ml_string.split()
currentQuestion = 0


for blank in ml_string:
replacement = blank_in_quiz(blank, blanks,)
if replacement != None:
user_input = raw_input("Type in the answer for blank " + replacement + " ")
while user_input != allanswers[selectedLevel][currentQuestion]:
print "Incorrect!"
user_input = raw_input("Type in the answer for blank " + replacement + " ")
else:
blank = blank.replace(replacement, user_input)
replaced.append(blank)
print "\nCorrect!\n"
print " ".join(replaced + [currentQuestion,ml_string])
currentQuestion = currentQuestion + 1
else:
replaced.append(blank)
replaced = " ".join(replaced)
print replaced

本质上,它的作用是获取这个字符串,即 ml_string:

"The movie __1__ is a war movie directed by __2__ Nolan about the __3__ and French armies stranded on the __4__ of Dunkirk while the __5__ army closed in on them."

一旦用户将正确答案添加到空白处,我就会尝试打印出空白处填写的答案,以及测验的其余部分以及他们尚未回答的空白。

我是 python 的初学者,但我一直在处理列表和索引值方面遇到困难。如果您想查看全文:https://repl.it/KTJh/16

第 55 行是我遇到的问题。感谢您提供任何建议。

最佳答案

您可以使用string formatting使用占位符(replacement_field)创建字符串,并用一些预定义的变量填充,当用户回答时,您只需更改变量即可。格式规范允许命名占位符

s = "The movie {ans1} is a war movie directed by {ans2} Nolan about the {ans3} and French armies stranded on the {ans4} of Dunkirk while the {ans5} army closed in on them."

这样可以方便地用字典填充占位符

d = {'ans1' : '__1__', 'ans2' : '__2__',
'ans3' : '__3__', 'ans4' : '__4__',
'ans5' : '__5__'}

你可以像这样使用它:

>>> s.format(**d)
'The movie __1__ is a war movie directed by __2__ Nolan about the __3__ and French armies stranded on the __4__ of Dunkirk while the __5__ army closed in on them.'

像这样更改答案

>>> d['ans1'] = 'Ziegfield Follies'
>>> s.format(**d)
'The movie Ziegfield Follies is a war movie directed by __2__ Nolan about the __3__ and French armies stranded on the __4__ of Dunkirk while the __5__ army closed in on them.'
>>>

关于python - 将某些内容添加到字符串后,如何打印修改以及字符串的其余部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45901576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com