这是我的代码:
bookings = ['blue,red', 'green,orange', 'yellow, purple']
number = 0
b = 0
c = 1
file_test = open('test_1.txt' , 'wt')
results_song = []
for item in bookings:
words = bookings[number].split(',')
results_song.append(words[0])
results_song.append(words[1])
number = number + 1
results_song_str = '\n'.join(results_song)
print(results_song_str)
file_test.write(results_song_str)
file_test.close()
file_test = open('test_1.txt' , 'r')
line = file_test.readlines()
for item in bookings:
line_1 = line[b]
line_2 = line[c]
answer = input('If first word is then what is the second word')
if answer == line_2:
print('correct')
else:
print('wrong')
b = b + 2
c = c + 2
但是代码不会识别答案等于 line_2
。我不明白为什么会这样。我检查过 c
是正确的数字并且 line_2
与答案相同。但我确实注意到,当我在打印 answer 和 line_2
时运行代码时,这将返回:
red
red
但我从未在此处添加新的线路功能。
任何帮助将不胜感激,因为我需要将此代码用于学校作业。
最佳答案
打印调试
# ...
for item in bookings:
line_1 = line[b]
line_2 = line[c]
print("Your Answer:", repr(answer))
print("Actual Answer:", repr(line_2))
# ...
给予
Your Answer: 'red'
Actual Answer: 'red\n'
啊哈!一个偷偷摸摸的换行符!似乎当程序从文件中读取文本并拆分行时,它为您保存了换行符。多么甜蜜烦人。 : |
要删除它,可以使用str.replace()
方法
# ...
for _ in range(len(bookings)): # I took the freedom to modify the loop conditions
line_1 = line[b].replace('\n','')
line_2 = line[c].replace('\n','')
# ...
或者更改从文件中读取行的方式,使用 str.split()
方法手动拆分行
# ...
with open('test_1.txt' , 'r') as file_test:
line = file_test.read().split('\n')
for _ in range(len(bookings)):
line_1 = line[b]
line_2 = line[c]
# ...
感谢 @juanpa.arrivillaga 建议使用 repr()
检查值。
关于python - 我有两个变量,我知道它们是相等的,但我的 if 语句不能识别这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53306474/