将一个字符串与从 .readlines() 返回的字符串进行比较总是给出 False

Comparing a string with the one returned from `.readlines()` always gives False

现在我的 if 语句似乎没有记录另一个变量等于一个声明的变量。我什至打印了存储的变量,猜测是要检查的,并且猜测和存储的变量应该彼此相等。

我试过让它区分大小写,也试过不区分大小写。我试过显示变量然后准确地输入它,但它不起作用。

import random
from random import randint

loop = 0
score = 0


f = open("songs.txt", "r")
line_number = randint(0,3)
lines = f.readlines()
songname = lines[line_number]

firstletters = songname.split()
letters = [firstletters[0] for firstletters in firstletters]
print(" ".join(letters))

f.close()

f = open("artists.txt", "r")
lines = f.readlines()
artistname = lines[line_number]

print("The first letter of each word in the title of the song is: " + "".join(letters))
print("The artist of the above song is: " + artistname)

print(songname)

answer = songname

guess = input("What is your guess? ")

if guess.lower()==answer:
  score = score + 3
  print("Correct! You have earned three points, and now have a total of:",score, "points!")

else:
  print("Incorrect! You have one more chance to guess it correctly!")
  guesstwo = input("What is your second guess? ")

  if guesstwo.lower()==answer:
    score = score + 1
    print("Correct! You have earned one point, and now have a total of:",score, "points!")

  else:
    print("Incorrect! Unfortunately you have guessed incorrectly twice- therefore the game has now ended. You had a total of:",score,"points!")

如果 "guess" 变量等于 songname 变量,那么它应该显示 "Correct! You have earned three points, and now have a total of:",score, "points!" 消息,尽管现在它总是显示 Song is Incorrect 消息。

文件中存储的歌曲有:

Africa
Redding
Follow
Fleekes

readlines 不会去除每行末尾的换行符。如果你 print(repr(songname)),你会看到它的末尾有一个 \n。您可以自己致电 strip 来解决此问题:

songname = lines[line_number].strip()

也许通过将答案也转换为小写字母。

if guess.lower() == answer.lower():