with open('33.txt') as text:
for line in text:
line2 = line[:][::-1]
if line == line2:
print ('Palindrome!')
我试图检查文件中的文本行是否是回文,但是当我运行代码时,似乎只检查最后一行是否是回文。我希望代码检查每一行的回文,我已经做了类似的程序,但在代码中使用字符串,我使用类似的方法,但我不知道为什么它不起作用。
答案 0 :(得分:4)
问题是除了最后一行之外的所有行都需要删除末尾的换行符。您可以使用strip
解决问题:
with open('33.txt') as text:
for line in text:
line = line.strip()
line2 = line[::-1]
if line == line2:
print ('Palindrome!')
答案 1 :(得分:0)
尝试以下几点:
with open('/usr/share/dict/words') as f:
for line in f:
line=line.strip() # You need to remove the CR or you won't find palindromes
if line==line[::-1]: # You can test and reverse in one step
print(line)