python - 回文比较未检测到某些情况
问题描述
如果单词/行是回文,我想打印 True 。代码从文本文件中读取文本(使用 sys.argv[1])。我不明白为什么它只检查第一行。
文本文件:
racecar
AddE
HmllpH
Was it a car or a cat I saw
Hannah
T can arise in context where language is played wit
Able was I ere I saw Elba
Doc note I dissent A fast never prevents a fatness I diet on cod
代码:
import sys
filename = sys.argv[1]
with open(filename, "r") as f:
text = f.readline().strip().lower()
while text:
palindrome = True
i = 0
while i < len(text) / 2:
if text[i] != text[len(text) - 1 - i]:
palindrome = False
i += 1
if palindrome:
print(True)
text = f.readline().strip()
输出:
True
解决方案
- 为什么只打印第一行?
只有第一行是区分大小写的回文。
- 代码修复:
关于你所看到的一些解释:
2.1。loop for text in map(str.strip, f)
,意味着我们正在遍历文件f
行并将该str.strip()
方法应用于每个行。
2.2. text.upper()
将文本转换为统一的大写,以进行通用比较。
2.3. text_upper[::-1]
反转文本:奇怪的[::-1]
索引表示法,意味着我们将所有元素向后移动一步(因此 -1)。
import sys
filename = 'outfile.txt'
with open(filename, "r") as f:
for text in map(str.strip, f):
text_upper = text.upper()
if text_upper == text_upper[::-1]:
print(f'{text} is palindrom!')
推荐阅读
- java - 在 java oracle 中我如何绑定值,java.sql.SQLException: Missing IN or OUT parameter at index::
- postgresql - 是否有任何方法可以仅备份 pgAdmin 4 中的选定表?
- snowflake-cloud-data-platform - 外部表特权
- c# - X509certificate2 安全警告
- django - 在序列化程序中计算后保存到模型
- javascript - 在功能组件中使用 useSelector 时挂钩调用无效
- apache-kafka - Kafka 控制台消费者中的暂停和恢复
- python - 如何在没有多重拟合的情况下将最佳拟合线拟合到曲线,或者是否有替代方法
- linux - Ubuntu Docker 安装;什么是稳定的存储库?
- javascript - 显示空内容的弹出模型