python - 我有两个变量,我知道它们是相等的,但我的 if 语句不能识别这个?

标签 python python-3.x if-statement

这是我的代码:

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/

相关文章:

Java For 循环数据验证

python - 从 PythonMagick 图像获取像素数据?

python - Tkinter 的 .pack() 格式问题

python - Anaconda 已安装但无法启动 Navigator

python-3.x - 插补和插补有什么区别?

python - 如何为 python 3 和 python 2 运行 pip

python - 不确定 'and' 操作

python - Python 中 Azure Functions 上的文件操作

java - boolean 变量

javascript - 如何让随机选择引用先前的 RPG 生命路径生成器的随机选择?