簡體   English   中英

在python中將字符串與字符串進行比較時,它會為false

[英]Compare string to string gives false when it should be true in python

我當時在做一個簡單的比較字符串,但結果卻是錯誤的。

我認為這是在行末比較“ \\ n”字符,但不確定。

有趣的是,當您比較每個列表的姓氏時,它的確會拋出TRUE。

  1. 創建循環以檢查對象列表中的每個文件

  2. 檢查男孩名字列表.. boys.txt

  3. 檢查女孩名字列表.. girls.txt
  4. 如果在列表和索引位置,則輸出結果(不允許使用切片)

這是代碼boy.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)

通過搜索John結果

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

搜索蘇格蘭人的結果

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 !!!

解決方案很簡單,我更新了

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM