Python 我的if变量未触发
我试图用python做一个测验,它从文本文件中读取问题。我有一个变量叫做Python 我的if变量未触发,python,Python,我试图用python做一个测验,它从文本文件中读取问题。我有一个变量叫做ans,它应该是它从文件中读取的答案,我打印变量,它说它应该说什么,但如果我真的输入它,它会说它错了。 这是我的python代码: right = 0 wrong = 0 num = 0 quest = 0 history = open("history.txt", "r") lines = history.readlines() while quest != 3: quest = quest+1 num =
ans
,它应该是它从文件中读取的答案,我打印变量,它说它应该说什么,但如果我真的输入它,它会说它错了。
这是我的python代码:
right = 0
wrong = 0
num = 0
quest = 0
history = open("history.txt", "r")
lines = history.readlines()
while quest != 3:
quest = quest+1
num = num+1
print("Question", quest)
question = lines[num]
print(question)
num = num + 1
ans = lines[num]
print(ans)
answer = input()
answer = answer.lower()
if answer == ans:
print("correct")
right = right+1
else:
print("Wrong")
wrong = wrong+0
print("done")
我的history.txt文件的格式如下
Blank Line Blank Line
What is the capital of England?
london
What is 1+1?
2
多谢各位 由
history.readlines()
返回的字符串末尾有换行符,但由input()
返回的字符串没有换行符。使用rstrip()
从字符串中删除任何尾随空格
ans = lines[num].rstrip()
readlines()
在拆分字符串时留下一个换行符(\n
)。尝试使用设置ans
ans = lines[num].rstrip()
尝试单步执行您的程序。如果在读取文件后打印出行的内容,您将看到它有新的行字符:
>>> history = open("history.txt", "r")
>>> lines = history.readlines()
>>> lines
['Blank Line Blank Line\n', 'What is the capital of England?\n', 'london\n', 'What is 1+1?\n', '2']
您需要修剪换行符
ans=ans.rstrip(“\n”)
由于allready提到的a\n
保留在每行的末尾,我建议使用re.split('\n',yourFile)
将字符串拆分为行。在这种情况下,换行符通常不起作用。我很确定当您从文件中读取时,会有一个“新行字符”-也就是“\n”)。
看看这个:
a = "123"
b = "123\n"
print(a == b)
Output: False
但是:
print(repr(ans),“=?=”,repr(answer))
我相信您会很快看到您的问题…您需要从用户输入中删除换行符(或文件中的行)。在许多语言中,都是通过chomp
完成的。我不知道如何在Python中实现它,也不知道是.readlines
还是input()
为您实现它,但这可能就是问题所在。您可以很容易地打印两个字符串(包括封闭字符),以查看最后一个字符是否出现在新行中。这更像是一个注释,而不是答案。我认为这是解决给定问题的一个有用的替代方案。。。我认为更好的方法是,如果文件包含回车符和换行符,那么nevermindIt可能不起作用
a = "123"
b = "123\n"
print(a == b.rstrip())
True