Сравнение строки со строкой дает ложь, когда она должна быть истинной в питоне - PullRequest
0 голосов
/ 03 ноября 2018

Я делал простую строку сравнения, и она оказалась ложной.

Я думаю, что он сравнивает символ "\ n" в конце строки, но не уверен.

Интересно, что он выдает TRUE, когда вы сравниваете фамилию каждого списка.

ПСЕВДО

  1. Создать цикл для проверки каждого файла из списка объектов

  2. Проверка списка имен мальчиков .. boys.txt

  3. Проверка списка имен девушек .. girls.txt
  4. Вывод результата, если в списке и позиции индекса (не разрешено использовать слайс)

Вот код boys.txt

john
paul
andrew
judas
archie
scot

girls.txt

cassie
sam
josie
nadine
cathy

nameSearch.py ​​

def read_list(fileToOpen):
    thisFile = fileToOpen + ".txt"
    filez = open(thisFile, "r")    
    names = filez.readlines()    
    filez.close()

    return names

def findName(name, nameList):
    count = 0
    pos = -1

    for thisName in nameList:
        print("Comparing", name, "to", thisName)

        if name == thisName:
            print (name, "has been found !!!")
            pos = count
        else:
            print(name, "does not compare to", thisName)
            count += 1

    return

filesList = ["boys", "girls"]

name = input("What is the name of the child ? ")

for thisFile in filesList:
    nameList = read_list(thisFile)
    result = findName(name,nameList)

РЕЗУЛЬТАТ путем поиска Джона

What is the name of the child ? john
Comparing john to john

john does not compare to john

Comparing john to paul

john does not compare to paul

Comparing john to andrew

john does not compare to andrew

Comparing john to judas

john does not compare to judas

Comparing john to archie

john does not compare to archie

Comparing john to scot
john does not compare to scot

Результат поиска scot

What is the name of the child ? scot
Comparing scot to john

scot does not compare to john

Comparing scot to paul

scot does not compare to paul

Comparing scot to andrew

scot does not compare to andrew

Comparing scot to judas

scot does not compare to judas

Comparing scot to archie

scot does not compare to archie

Comparing scot to scot
scot has been found !!!

1 Ответ

0 голосов
/ 03 ноября 2018

Решение было достаточно простым, я обновил

def findName(name, nameList):
    count = 0
    pos = -1

    for thisName in nameList:
        print("Comparing", name, "to", thisName)
        aName = thisName.strip("\n")  ## <-- added this line
        if name == aName:
            print (name, "has been found !!!")
            pos = count
        else:
            print(name, "does not compare to", aName)
            count += 1

    return
...