Python returns false for "1" == "1". Any ideas why?
I wrote a scout system for my level A calculation task. The program is designed to store information about scouts in a scout hut, including badges, a leader system and a management system for adding / finding / removing scouts from the list. Scout information MUST be kept on file.
File handling process for delete function (where is my problem): The scout delete button launches a popup (using tkinter). The window collects the scout ID, then searches the scout file, checks the ID of the scouts found and compares it to the ID entered. If the identifier is found, it skips that line of the file, otherwise the line will be copied to the temporary file. After all lines are completed, the lines in temp are copied to a new empty version of the original file and delete / recreate the temp file as empty.
My problem: The problem is when the program compares the identifier to remove (remID) with the identifier of the currently checked scouts in the file (sctID), it returns false when in fact they are equal. It could be a problem with my variable handling, my splitting a string to get an id, or even my data types. I just do not know. I tried converting both to string, but still false. The code for this section is shown below. Thank you in advance!
elif self._name == "rem":
remID = str(scoutID.get())
if remID != "":
#store all the lines that are in the file in a temp file
with open(fileName,"r") as f:
with open(tempFileName,"a") as ft:
lines = f.readlines()
for line in lines:
sctID = str(line.split(",")[3])
print("%s,%s,%s"%(remID, sctID, remID==sctID))
#print(remID)
if sctID != remID: #if the ID we are looking to remove isn't
#the ID of the scout we are currently looking at, move it to the temp file
ft.write(line)
#remove the main file, then rectrate a new one
os.remove(fileName)
file = open(fileName,"a")
file.close()
#copy all the lines back to the main file
with open(tempFileName,"r") as tf:
lines = tf.readlines()
with open(fileName,"a") as f:
for line in lines:
f.write(line)
#finally, delete and recreate the temp file
os.remove(tempFileName)
file = open(tempFileName,"a")
file.close()
#remove the window
master.destroy()
My conclusion:
1,1
,False
1,2
,False
1,3
,False
source to share
When converting to a string, you hide the error.
Always try to retype (value) instead of str (value) for debugging purposes. You should also know that it is better to compare integers rather than strings. "1"! = "1".
Edit: It's clear from your output that you have an extra '\ n' (Newline) in the sctID. Since you are comparing strings this will always be False.
I am assuming you have either strings with extra spaces, other hidden characters, or just different value types, which would also provoke a different result.
source to share