2016-11-16 71 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)