I am trying to find a name that is in two separate lists I created and have a function check to see if it is there. I know it is checking the list and I have printed out the list to make sure it is stored correctly but it keeps giving me my error statement that the name is not found in the list. Here is the code I have for it.
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()
When I throw in a print statement like print(list1), it gives me the names in this format, ['Jacob\n', ....] and when I test it it prints out my else statement regardless of what I type in for the input. I have also tried checking it with the index function and it tells me that 'Jacob' is not in list if I try that. I feel like I have to be overlooking something because I've written similar code that works properly and this is almost a mirror image of it except with different data types.
\nadded to the name therefore when you enumerate over the file pointer you are readinglisyou are reading everything line by line including the newline character. You can just remove the newline after reading it in likeboyList.append(line.replace("\n", ""))