[英]Comparing Strings in an Array in Python
我有一個數組,在每個索引處存儲一個字符串。 我試圖比較用戶輸入到數組,以找到字符串所在的索引。 我可以確認用戶字符串和數組字符串實際上是相同的,但是並沒有給我真正的結果。 我也包括了示例輸出。 但是,如果我輸入“ 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
當您for line in tleFile:
使用for line in tleFile:
讀取for line in tleFile:
,每line
for line in tleFile:
都將包含終止\\n
字符。 這就是文件對象生成器的工作方式。 因此,您的字符串實際上並不完全相同,因為array[j]
在末尾有一個額外的換行符。 您實際上是在檢查'NOOA 16' == 'NOOA 16\\n'
返回False
。
您可以通過刪除比較的任何前導和尾隨空格字符的字符串來解決此問題:
if requestedSat.strip() == array[j].strip():
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.