将文本文件中的字母与变量进行比较 returns False

Comparing letters from a text file to a variable returns False

我正在尝试将字母列表与文本文件中的字母进行比较,一切正常,除了即使字母与文本文件中的字母相等;它会产生 False

下面是正在发生的事情的示例:

with open("Comparing_file") as f:
    for line in f:
        line = line.strip("") # removing the spaces(if there was any)
    
    letter = "A"    
    print("This is the line:", line)
    print("This is the letter:", letter)

    if letter.strip("") == line:  # removing the spaces(if there was any)
        print("equal")
    else:
        print("not equal")

结果如下:

This is the line: A  

This is the letter: A

not equal

你误用了 strip。

S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead.

这意味着,如果您为 strip 提供一个参数,它将删除该参数中的任何内容。在你的情况下,你提供了 "" 这是一个空字符串,这意味着 strip 基本上什么都不做。

相反,您可以尝试:

line.strip()
letter.strip()
# OR
line.strip(" ") # this for example will remove spaces.
line.strip("\n") # this for example will remove "\n".