[英]I have two variables that I know are equal but my if statement does not recognise this?
This is my code: 这是我的代码:
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
However the code will not recognise that answer is equal to line_2
. 但是,代码无法识别答案是否等于
line_2
。 I cannot figure out why this is happening. 我无法弄清楚为什么会这样。 I have checked that
c
is the correct number and that line_2
is the same as answer. 我检查过
c
是正确的数字,而line_2
与答案相同。 But I did notice that when I ran the code while printing answer and line_2
that this would return: 但是我确实注意到当我在打印answer和
line_2
时运行代码时会返回:
red
red
but I never put a new line feature in here. 但我从来没有在这里添加新的线路功能。
Any help would be much appreciated as I need to use this code for a school assignment. 我非常感谢任何帮助,因为我需要将此代码用于学校作业。
Debugging by printing 通过打印进行调试
# ...
for item in bookings:
line_1 = line[b]
line_2 = line[c]
print("Your Answer:", repr(answer))
print("Actual Answer:", repr(line_2))
# ...
gives 给
Your Answer: 'red'
Actual Answer: 'red\n'
Aha! 啊哈! A sneaky newline character!
一个偷偷摸摸的换行符! Seems like when the program was reading text from the file and splitting the lines, it saved the newline character for you.
好像当程序从文件中读取文本并拆分行时,它会为您保存换行符。 How sweetly annoying.
多么甜蜜烦人。 : |
:|
To remove it, you can use the str.replace()
method 要删除它,可以使用
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','')
# ...
or change the way lines are read from the file, manually splitting the lines using the str.split()
method 或者更改从文件中读取行的方式,使用
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]
# ...
Credit goes to @juanpa.arrivillaga for suggesting the use of repr()
to check values. 感谢@ juanpa.arrivillaga建议使用
repr()
来检查值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.