【问题标题】:Compare string to string gives false when it should be true in python比较字符串到字符串在python中应该为真时给出假
【发布时间】:2018-11-03 02:27:54
【问题描述】:

我在做一个简单的比较字符串,结果是假的。

我认为它是在行尾比较“\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)

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

【问题讨论】:

  • “我认为它比较的是行尾的“\n”字符,但不确定。” 我喜欢这个理论 :-) 我建议你测试一下出去。尝试将 print(nameList) 放在您的 read_list 调用下方,看看是否有任何条目在末尾有换行符。
  • ['john\n', 'paul\n', 'andrew\n', 'judas\n', 'archie\n', 'scot'] .. 是的..所以我必须这样做Name.strip("\n") 我认为.. 将在一秒钟内更新
  • 是的,这是在 findName 函数中 for 循环开始之后添加 aName = thisName.strip("\n") 的解决方案。希望这对其他人有帮助:-)

标签: python string compare newline


【解决方案1】:

解决方法很简单,我更新了

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

【讨论】:

    猜你喜欢
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 2012-05-16
    • 1970-01-01
    相关资源
    最近更新 更多