在Python中比较数组中的字符串

时间:2017-10-29 20:00:18

标签: python arrays compare

我有一个数组,在每个索引处存储一个字符串。我试图比较用户输入到数组,以找到字符串所在的索引。我可以确认用户字符串和数组字符串实际上是相同的,但它没有给我一个真实的结果。我也包含了一个示例输出。但如果我进入" noaa 16"它循环遍历数组,但错过了索引。

    import ephem
    import datetime
    requestedSat = raw_input("Please enter the satellite you want to track")
    requestedSat = requestedSat.upper() #format the users input to fit the file constraints.
    tleFile = open("t")
    i = 0
    array = [None] * 100 #need to create a link list of sorts to account for larger files. If a file as more than 100 lines we will have an index error
    for line in tleFile: #read thew the file, counting how many lines there are, as well as adding each line to an array index.
        array[i] = line.translate(None,"[+-]") #removing special characters form the array. I dont know if they are important yet.
        i+=1

    j=0
    found = False

    for x in xrange(0,i/3):
        print requestedSat
        print "array = " + array[j]
        if requestedSat == array[j]:
            print "found it"

        else:
            j+=3

这是输出。如您所见,用户键入NOAA 16,字符串值存储在数组中。如何让它准确地比较字符串

NOOA 16
array = NOAA 14              

NOOA 16
array = NOAA 15 B             

NOOA 16
array = NOAA 16              

NOOA 16
array = NOAA 17              

1 个答案:

答案 0 :(得分:0)

当您使用for line in tleFile:阅读行时,每个line将在末尾包含终止\n字符。这就是文件对象生成器的工作原理。所以你的字符串实际上并不相同,因为array[j]在结尾处有一个额外的换行符。您有效检查'NOOA 16' == 'NOOA 16\n'是否返回False

您可以通过剥离任何前导和尾随空格字符的比较字符串来解决此问题:

if requestedSat.strip() == array[j].strip():