Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Python:将文件行读取后拆分的字符串与返回false的输入进行比较_String_Python 3.x_File_Split - Fatal编程技术网

String Python:将文件行读取后拆分的字符串与返回false的输入进行比较

String Python:将文件行读取后拆分的字符串与返回false的输入进行比较,string,python-3.x,file,split,String,Python 3.x,File,Split,我试图从文本文件(都存储在同一行)中读取问题和答案。然后,我将使用逗号delimeter分割行,将值存储到两个变量中。我将向用户显示问题,用户将回答。然后将用户输入与文件中的答案进行比较。然后根据答案是否正确显示一条消息 我的代码如下: File = open("Quiz.txt", "r") for Line in File: Question, Answer = Line.split(',', 1) UserAnswer = input(Question) if(Us

我试图从文本文件(都存储在同一行)中读取问题和答案。然后,我将使用逗号delimeter分割行,将值存储到两个变量中。我将向用户显示问题,用户将回答。然后将用户输入与文件中的答案进行比较。然后根据答案是否正确显示一条消息

我的代码如下:

File = open("Quiz.txt", "r")
for Line in File:
    Question, Answer = Line.split(',', 1)
    UserAnswer = input(Question)
    if(UserAnswer == Answer):
        print("Correct")
    else:
        print("Incorrect")
File.close()
Q1) What is a Variable used for?,Storage
Q2) How many bits in a Byte?,8
Q3) How many Bytes in a Kilobyte?,1024
我的测验文件如下:

File = open("Quiz.txt", "r")
for Line in File:
    Question, Answer = Line.split(',', 1)
    UserAnswer = input(Question)
    if(UserAnswer == Answer):
        print("Correct")
    else:
        print("Incorrect")
File.close()
Q1) What is a Variable used for?,Storage
Q2) How many bits in a Byte?,8
Q3) How many Bytes in a Kilobyte?,1024
文件读入,我使用print语句查看变量中存储了哪些值。除了用户输入和存储值之间的比较返回false(第5行)之外,所有结果都显示良好。我甚至尝试将值强制转换为字符串,而comparison仍然返回false


我知道我可能忽略了一些显而易见的东西,需要另一双眼睛。感谢您的帮助。

答案上的最后一个字符是换行符。尝试:

UserAnswer == Answer[:-1]

“[:-1]”从字符串中删除最后一个字符。

您正在比较内存中的两个位置。你要比较这两个地方的内容。