with open('33.txt') as text:
for line in text:
line2 = line[:][::-1]
if line == line2:
print ('Palindrome!')我试图检查文件中的文本行是否为回文,但当我运行代码时,似乎只检查最后一行是否为回文。我希望代码检查回文的每一行,我已经做了类似的程序,但是在代码中使用了字符串,我正在使用类似的方法,但是我不知道为什么它不能工作。
发布于 2016-11-16 02:22:12
问题是,除了最后一行之外,所有行的末尾都有换行符,需要删除。您可以用strip解决这个问题。
with open('33.txt') as text:
for line in text:
line = line.strip()
line2 = line[::-1]
if line == line2:
print ('Palindrome!')发布于 2016-11-16 02:24:18
试一试以下几种方法:
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)https://stackoverflow.com/questions/40622984
复制相似问题