I need to open a .txt file and iterate through it looking for a palindrome. My loop will iterate through the file but is not returning anything even though I know that there are palindromes in the file. It will only print out a bunch of empty brackets when I run it.
file = open("dictionary.txt", "r")
lst = []
for word in file:
if(len(word) > 1 and word == word[::-1]):
lst = lst.append(word)
print(lst)
lst.append(word)
appends the word to the list
and doesn't return anything. Your code lst = lst.append(word)
is appending the word to lst
and overwriting it by assigning None
which is returned by append
.
You're indeed appending correctly, but getting the return value of the append statement, which is nonsense.
Replace the following line:
lst = lst.append(word)
by
lst.append(word)
And that's all.
You should strip
your string. Moreover, append
modifies the original list and returns None
.
file = open("dictionary.txt", "r")
lst = []
for word in file:
word=word.strip()
if(len(word) > 1 and word == word[::-1]):
lst.append(word)
print(lst)
您必须将文件的内容分配给变量
var = file.read()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.