[英]an item of list is not being equal to one another
我正在创建一个项目游戏,其中将包含回文词我有一个所有英文单词的列表,我想检查列表中的每个单词并找到彼此相等的单词
file1 = open ('words.txt')
file2reversed = open ('words.txt')
words = file1.readlines()
print(words[3][::-1])
print()
if words[3][::-1] == words[3]:
print("equal")
else:
print("not")
我的代码是这样的,我把第三个词写成回文词,想检查它是否正常工作,output 看起来像这样
aaa
aaa
not
为什么words[3][::-1]
不等于words[3]
即使它是回文词?
使用file.read().splitlines()
代替。 file.readlines()
返回的行在末尾的每个字符串后附加了一个换行符,因此当反转时, '\naaa' != 'aaa\n'
。
更干净
file = open('words.txt')
text = file.read()
words = text.splitlines()
# words is a list of strings without '\n' at the end of each line.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.