gpt4 book ai didi

Python 向 "1"= ="1"返回 false。任何想法为什么?

转载 作者:太空宇宙 更新时间:2023-11-03 12:38:59 25 4
gpt4 key购买 nike

我为我的 A Level 计算任务编写了一个侦察系统。该程序旨在将球探的信息存储在球探小屋中,包括徽章、排行榜系统以及用于从列表中添加/查找/删除球探的管理系统。侦察信息必须存储在文件中。

删除函数的文件处理过程(我的问题所在):删除侦察按钮触发弹出窗口(使用 tkinter)。该窗口收集侦察员的 ID,然后搜索侦察员文件,扫描存储的侦察员 ID 并将其与输入的 ID 进行比较。如果找到 ID,它将跳过文件的这一行,否则将该行复制到临时文件。完成所有行后,temp 中的行将复制到原始文件的新空白版本,并删除/重新创建临时文件为空白。

我的问题:问题是当程序将要删除的 ID (remID) 与文件中当前正在查看的侦察员的 ID (sctID) 进行比较时,它会返回 false,而实际上它们是相等的。这可能是我对变量的处理、我拆分行以获取 ID 甚至我的数据类型的问题。我只是不知道。我尝试将两者都转换为字符串,但仍然是错误的。此部分的代码如下。提前致谢!

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()

我的输出:

1,1
,False
1,2
,False
1,3
,False

最佳答案

通过转换为字符串,您可以隐藏错误。

出于调试目的,始终尝试使用 repr(value) 而不是 str(value)。您还应该知道,最好比较整数而不是字符串——例如“1”!=“1”。

Edit: From your output, it is clear that you have an extra '\n' (Newline) in the sctID. Because you compare strings, this will be always be False.

我想,您可能有带有额外空格或其他隐藏字符的字符串,或者只是不同类型的值,这也会导致不同的结果。

关于Python 向 "1"= ="1"返回 false。任何想法为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30923049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com