python - 未附加列表
问题描述
我需要打开一个 .txt 文件并遍历它以寻找回文。我的循环将遍历文件,但没有返回任何内容,即使我知道文件中有回文。当我运行它时,它只会打印出一堆空括号。
file = open("dictionary.txt", "r")
lst = []
for word in file:
if(len(word) > 1 and word == word[::-1]):
lst = lst.append(word)
print(lst)
解决方案
你应该strip
你的字符串。此外,append
修改原始列表并返回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)
推荐阅读
- python - Python 网页抓取 Asos 错误的问题
- c++ - 为 Edge TPU 构建 TensorFlow Lite 失败
- asp.net - 无法读取配置节“安全”,因为它缺少节声明
- api - Microsoft Graph 订阅 API 开始返回没有位置的 HTTP 308
- c++ - 如何在没有项目的情况下链接 CodeBlocks 中的 2 个文件?
- postgresql - 使 Azure Postgres 与 Azure SQL 保持同步的最佳方式
- apache - 访问远程 Mercurial 服务器时,我只打印了 hgweb.cgi python 脚本
- javascript - 使用 Mocha 在浏览器中测试音频(需要用户交互)
- excel - 如何在 VBA 中更改数组中数字的格式
- powershell - 获取在服务器上打开文件的计算机的 IP 地址