简体   繁体   English

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

[英]Comparing Strings in an Array in Python

I have an array that stores a string at each index. 我有一个数组,在每个索引处存储一个字符串。 I am trying to compare a users input to the array, to find the index the string is located. 我试图比较用户输入到数组,以找到字符串所在的索引。 I can confirm that the user string and the array string is infact the same, but it is not giving me a true result. 我可以确认用户字符串和数组字符串实际上是相同的,但是并没有给我真正的结果。 I have included a sample output as well. 我也包括了示例输出。 But if i enter "noaa 16" it cycles through the array, but misses the index. 但是,如果我输入“ 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

Here is the output. 这是输出。 As you can see, the user typed NOAA 16, and the string value is stored in the array. 如您所见,用户键入NOAA 16,并且字符串值存储在数组中。 How can i get it to compare the strings accurately 我怎样才能准确地比较字符串

NOOA 16
array = NOAA 14              

NOOA 16
array = NOAA 15 B             

NOOA 16
array = NOAA 16              

NOOA 16
array = NOAA 17              

When you read lines using for line in tleFile: , each line will contain the terminating \\n character at the end. 当您for line in tleFile:使用for line in tleFile:读取for line in tleFile: ,每line for line in tleFile:都将包含终止\\n字符。 That's just how the file object generator works. 这就是文件对象生成器的工作方式。 So your strings are, in fact, not identical, because array[j] has an extra line break at the end. 因此,您的字符串实际上并不完全相同,因为array[j]在末尾有一个额外的换行符。 You're in effect checking whether 'NOOA 16' == 'NOOA 16\\n' , which returns False . 您实际上是在检查'NOOA 16' == 'NOOA 16\\n'返回False

You could solve this by stripping the compared strings of any leading and trailing whitespace characters: 您可以通过删除比较的任何前导和尾随空格字符的字符串来解决此问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM