Python中readlines()读取字符串与输入字符串比对恒为False的问题
问题根源:
readlines()保留了换行符 你遇到的问题其实很常见——readlines()方法读取文件时,会把每一行末尾的**换行符\n(Windows下是\r\n)**也一并读进字符串里。比如你的songs.txt里第一行是Africa,用readlines()读出来的songname实际是"Africa\n",而你输入的猜测值是"Africa",两者看起来一样,但实际是不同的字符串,所以比对永远失败。
修复方案
有两种简单的方法可以解决这个问题:
方法1:用strip()去除字符串两端的空白字符
在读取每行内容后,调用strip()方法,它会自动去掉字符串开头和结尾的换行符、空格、制表符等空白字符。修改你的代码如下:
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].strip() firstletters = songname.split() # 修正变量名重复问题,避免覆盖 letters = [word[0] for word in firstletters] print(" ".join(letters)) f.close() f = open("artists.txt", "r") lines = f.readlines() # 同样处理艺术家名称 artistname = lines[line_number].strip() 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.lower(): 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.lower(): 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!")
方法2:用splitlines()代替readlines()
splitlines()方法会自动按换行分割内容,并且不保留换行符,代码修改如下:
# 读取songs.txt时替换readlines() lines = f.read().splitlines() songname = lines[line_number] # 读取artists.txt时同理 lines = f.read().splitlines() artistname = lines[line_number]
额外提示
你原来代码里的letters列表推导式存在变量名重复的问题(firstletters被循环变量覆盖),我已经改成了[word[0] for word in firstletters],这样代码逻辑更清晰,也避免了潜在的bug。
内容的提问来源于stack exchange,提问作者Ben Hams
相关产品推荐
相关产品推荐

