所以标题可能没有意义。但这是代码:
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行是我遇到的麻烦。感谢您的任何建议。
答案 0 :(得分:2)
您可以使用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.'
>>>
答案 1 :(得分:0)
假设您正在使用最新的Python学习(3.6),您可以使用f-strings。花括号中的项可以是大多数Python表达式。在这种情况下,他们索引一个单词列表:
import textwrap
def paragraph(words):
s = f'The movie {words[0]} is a war movie directed by {words[1]} Nolan about the {words[2]} and French armies stranded on the {words[3]} of Dunkirk while the {words[4]} army closed in on them.'
print()
print(textwrap.fill(s))
words = '__1__ __2__ __3__ __4__ __5__'.split()
paragraph(words)
words[0] = 'Dunkirk'
paragraph(words)
输出:
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.
The movie Dunkirk 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.