2016-11-16 45 views
0
with open('33.txt') as text: 
    for line in text: 
     line2 = line[:][::-1] 
     if line == line2: 
      print ('Palindrome!') 

我想检查文件的行是否是palindromes,但是当我运行代码时,它似乎只检查最后一行是否是回文。我想让代码检查每一行的palindromes,我做了类似的程序,但在代码中使用了字符串,我使用了类似的方法,但我不知道为什么它不起作用。Python 3文本文件中的回文

+1

无需额外的'[:]'只是做'线[:: - 1]' – dawg

回答

3

问题是除了最后一行之外的所有行在末尾都有换行符,需要删除。你可以用strip解决问题:

with open('33.txt') as text: 
    for line in text: 
     line = line.strip() 
     line2 = line[::-1] 
     if line == line2: 
      print ('Palindrome!') 
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)