为什么两个相同的字符串在比较时不返回相同的结果?

2024-10-01 04:49:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

file = open('AdjectivesList.txt', 'r')
lines = file.readlines()
file.close()

for word in words:
    wordLowercase = word.lower()
    for x, lol in enumerate(lines):
       gg = (lines[x].lower())
       if wordLowercase == gg:
            print('identified')

即使wordLowercase等于gg,也不会打印字符串“identified”。为什么会这样?你知道吗


Tags: 代码intxtforcloseopenlowerword
1条回答
网友
1楼 · 发布于 2024-10-01 04:49:29

.readlines()在文本文件的每一行末尾都包含换行符。这很可能是你的问题的原因。可以使用.strip()删除换行符(以及字符串左右两侧的任何空格字符)。你知道吗

gg = lines[x].lower().strip()

参考

相关问题 更多 >