gpt4 book ai didi

python - 字符串无法正确比较

转载 作者:行者123 更新时间:2023-12-01 05:19:47 25 4
gpt4 key购买 nike

我是 python 新手,所以请原谅您可能发现的任何糟糕的代码

我遇到的问题是我正在尝试比较两个字符串,一个来自文件,一个来自用户输入,以查看它们是否匹配。然而,当比较在我看来相同的字符串时,if 语句返回 false。我已经使用 str() 函数将这两个值都转换为字符串,但它仍然不想发挥作用。

作为引用,文件的行是两个字符串,用逗号分隔,“问题”部分位于逗号之前,“答案”部分位于逗号之后。目前,这两个字符串都是测试字符串,因此有“Question”和“Answer”的值

import linecache
def askQuestion(question, answer):
choice = input(question)
str(choice)
if choice == answer:
print("Correct")
else:
print("Bad luck")
file = "C://questions.txt"
text = linecache.getline(file, 1)
question = text.split(",", 1)[0]
answer = text.split(",", 1)[-1]
str(answer)
askQuestion(question, answer)

我正在准确地输入文件的内容,即在正确的位置输入大写字母,以供注意。我确信答案很明显,但我不知所措,所以任何帮助将不胜感激。

谢谢!

最佳答案

text = linecache.getline(file, 1)
question = text.split(",", 1)[0]
answer = text.split(",", 1)[-1]

这是更常见的写法

text = linecache.getline(file, 1)
question, answer = text.split(",", 1)

结果将是一个字符串。没有发生任何解释。另外,您需要存储 str() 的结果。

my_string = str(number)

通过调用 str() 但不保存结果会丢失。这里并不重要,但需要记住一些事情。

正如 Alex 在上面的评论中提到的,您错过了对 strip 的调用来删除换行符。我怎么知道?我在解释器中尝试过。

$ python
>>> import linecache
>>> line = linecache.getline("tmpfile", 1)
>>> line

'* 联系电​​话\n'

看到那里的“\n”了吗?那是你的问题。

另一种方法是调用 Python 调试器 pdb。只需添加

import pdb; pdb.set_trace()

您想要停止执行 Python 脚本的位置。

祝你好运。

关于python - 字符串无法正确比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22620263/

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