我试图在我创建的两个单独列表中找到一个名称,并使用函数检查它是否存在。我知道它正在检查列表并且我已经打印出列表以确保它被正确存储但是它一直给我错误声明在列表中找不到该名称。这是我的代码。
def readBoyFiles():
boyfile = 'BoyNames.txt'
boyList = []
with open(boyfile, 'r') as lis:
for line in lis:
boyList.append(line)
return boyList
def readGirlFiles():
girlfile = 'GirlNames.txt'
girlList = []
with open(girlfile, 'r') as names:
for line in names:
girlList.append(line)
return girlList
def nameInput():
name = input('Please enter the name you would like to search: ')
list1 = readBoyFiles()
list2 = readGirlFiles()
findName(name, list1)
findName(name, list2)
def findName(name, list):
if name in list:
print('This name is among the most popular!')
else:
print('This name is not among the most popular.')
nameInput()
当我输入像 print(list1) 这样的打印语句时,它会以这种格式 ['Jacob\n', ....] 给我名字,当我测试它时它会打印出我的 else 语句我输入的内容。我还尝试使用索引函数检查它,如果我尝试这样做,它会告诉我“Jacob”不在列表中。我觉得我必须忽略一些东西,因为我编写了可以正常工作的类似代码,这几乎是它的镜像,只是数据类型不同。
最佳答案
记得剥掉你的绳子!它删除前导和尾随空格。从技术上讲,“Jacob”不在列表中,因为“Jacob\n”在列表中。
def readBoyFiles():
boyfile = 'BoyNames.txt'
boyList = []
with open(boyfile, 'r') as lis:
for line in lis:
boyList.append(line.strip())
return boyList
def readGirlFiles():
girlfile = 'GirlNames.txt'
girlList = []
with open(girlfile, 'r') as names:
for line in names:
girlList.append(line.strip())
return girlList
关于python - 从 Python 3 中的文件生成的列表中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54890264/