python - 改进 Python 回文代码

标签 python palindrome simplify

所以我最近实现了一个代码来检查一个单词是否是回文。

def isPalindrome():
    string = input('Enter a string: ')
    string1 = string[::-1]
    if string[0] == string[(len(string)-1)] and string[1:(len(string)-2)] == string1[1:(len(string)-2)]:
            print('It is a palindrome')
    else:
        print('It is not a palindrome')
isPalindrome()

我想知道是否有人可以给我一些简化代码的提示。

编辑 - 如果我要使用语句 string == string1 使该函数成为迭代函数,我将如何停止无休止的 while 循环?我需要计数来停止 while 循环吗?

最佳答案

不需要这么复杂的条件。您已经有一个反转的字符串 (string[::-1])。

您需要做的就是:

def isPalindrome():
    string1 = input('Enter a string: ')
    string2 = string1[::-1]
    if string1 == string2:
        return 'It is a palindrome'
    return 'It is not a palindrome'

isPalindrome()

(顺便说一句,不要使用 string 作为变量名。那是内置模块的名称)

最好返回 字符串而不是打印它们。这样你的函数就不会返回 None(防止一些以后可能发生的事情)

关于python - 改进 Python 回文代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19368509/

上一篇:Python CSV 模块

下一篇:Python无限循环

相关文章:

java - 使用堆栈的回文类的问题

c - 在 C 中打印时得到 ╠

c - 它是基于命令行的 C 程序来检查回文字符串,我的答案是正确的,但我必须在终端中提供参数 2 次

mysql - ColdFusion DateDiff - 有更好的方法吗?

python - 如何解析简单的带引号的字符串(处理转义)

python - 在脚本评估期间删除临时文件

Python,加拿大地址正则表达式验证

postgresql - Postgis - 如何简化多边形的起点

algorithm - 简化数学表达式的策略

python - 属性错误 : Menu instance has no attribute '__len__'