在python

时间:2018-11-03 02:27:54

标签: python string compare newline

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

我认为它是在行尾比较“ \ n”字符,但不确定。

有趣的是,当您比较每个列表的姓氏时,它的确会抛出TRUE。

PSEUDO

  
      
  1. 创建循环以检查对象列表中的每个文件

  2.   
  3. 检查男孩名字列表。.boys.txt

  4.   
  5. 检查女孩名字列表.. girls.txt
  6.   
  7. 如果在列表和索引位置(不允许使用切片),则输出结果
  8.   

这是代码 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

通过苏格兰语搜索结果

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 :(得分:0)

解决方案很容易,我更新了

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