Python,从文件读取 -> 将文件内容添加到列表 -> 将列表与用户输入进行比较
Python, read from file -> add file content to list -> compare list to user input
好的,正如标题所述,我正在从 txt 文件中检索单词,然后将其添加到列表中,然后尝试将列表的内容与用户输入进行比较。
X = []
Y = open(‘file.txt’,’r’)
X.append(Y.read())
Z = input(‘I’)
A = X[0]
if Z == A:
print(‘y’)
我比较了类型并且它们匹配,尝试了 python 2&3 但没有。我也试过使用预设数组,效果很好。我试过将两半分成功能,但仍然没有。
Repr 给出:
列表='a\n'
输入 = ‘a’
您正在从文件中读取的字符串末尾有一个新行。
您可以使用 strip()
(remove surrounding whitespace) or rstrip()
(删除尾随空格)轻松删除它。
例如:
if Z == A.strip():
print("y")
这有帮助吗?
with open("test.txt", "r") as f:
data = f.read().strip()
user_input = input('Please enter something: ')
if user_input == data:
print('Correct!')
else:
print('FALSE')
好的,正如标题所述,我正在从 txt 文件中检索单词,然后将其添加到列表中,然后尝试将列表的内容与用户输入进行比较。
X = []
Y = open(‘file.txt’,’r’)
X.append(Y.read())
Z = input(‘I’)
A = X[0]
if Z == A:
print(‘y’)
我比较了类型并且它们匹配,尝试了 python 2&3 但没有。我也试过使用预设数组,效果很好。我试过将两半分成功能,但仍然没有。
Repr 给出: 列表='a\n' 输入 = ‘a’
您正在从文件中读取的字符串末尾有一个新行。
您可以使用 strip()
(remove surrounding whitespace) or rstrip()
(删除尾随空格)轻松删除它。
例如:
if Z == A.strip():
print("y")
这有帮助吗?
with open("test.txt", "r") as f:
data = f.read().strip()
user_input = input('Please enter something: ')
if user_input == data:
print('Correct!')
else:
print('FALSE')