[英]I have two variables that I know are equal but my if statement does not recognise this?
這是我的代碼:
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()
來檢查值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.