Python 将字符串与从`.readlines()`返回的字符串进行比较总是会得到False

Python 将字符串与从`.readlines()`返回的字符串进行比较总是会得到False,python,python-3.x,string,readlines,Python,Python 3.x,String,Readlines,现在我的if语句似乎没有注册另一个变量等于一个声明的变量。我甚至已经打印了存储的变量,猜测是用来检查的,猜测和存储的变量应该是相等的 我已经尝试过使它区分大小写,并且没有。我试图显示变量,然后准确地键入它,但它就是不起作用 import random from random import randint loop = 0 score = 0 f = open("songs.txt", "r") line_number = randint(0,3) lines = f.readlines()

现在我的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
变量,那么它应该显示
“正确!您已经获得三分,现在总共有:”,score,“points!”
消息,尽管现在它总是显示
歌曲不正确
消息

文件中存储的歌曲有:

Africa
Redding
Follow
Fleekes

readlines
不会从每行末尾删除换行符。如果您打印(repr(songname)),您将看到它的末尾有一个
\n
。您可以通过自己调用
strip
来解决此问题:

songname = lines[line_number].strip()

也许通过将答案转换成小写

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

你能打印猜测和答案只是为了再次检查吗?可能是重复的,而不是将整行读取到内存中,使用
islice
直接从iterable中获取所需的行(无需读取超出实际需要的内容)。例如,
songname=next(islice(f,linenumber,None)).strip()
。你仍然需要阅读每一行,直到你得到你想要的那一行,但是每一行不需要的内容在阅读时都会被丢弃,而不是保留在记忆中。谢谢你,但这没有什么区别——帕特里克·豪夫的建议似乎已经纠正了这一点。我非常感谢你的回信。@BenHams为什么你接受这个答案,而不是Patrick的答案?