【问题标题】:Palindrome Function Python回文函数 Python
【发布时间】:2016-03-11 03:32:40
【问题描述】:

我正在尝试编写一个函数来告诉我输入的单词或短语是否是回文。到目前为止,我的代码有效,但仅适用于单个单词。我将如何做到这一点,如果我输入带有空格的东西,比如“赛车”或“不靠邪恶生活”,该函数将返回 true?此页面上的其他问题解释了如何用一个词而不是多个词和空格来做。这是我到目前为止所拥有的......

def isPalindrome(inString):
    if inString[::-1] == inString:
        return True
    else:
        return False

print 'Enter a word or phrase and this program will determine if it is a palindrome or not.'
inString = raw_input()
print isPalindrome(inString)

【问题讨论】:

  • @willnx:如果我错了,请纠正我。我认为您的链接是关于查看一个单词是否是回文的问题,但这个问题是查看整个句子是否是。区分这听起来可能很荒谬,但是“女士我亚当”在您的链接中不起作用。 (如果我没看错的话。)

标签: python function palindrome


【解决方案1】:

如果字符不是空格,您可以将字符串的字符添加到列表中。代码如下:

def isPalindrome(inString):
    if inString[::-1] == inString:
        return True
    else:
        return False

print 'Enter a word or phrase and this program will determine if it is a palindrome or not.'
inString = raw_input()
inList = [x.lower() for x in inString if x != " "]  #if the character in inString is not a space add it to inList, this also make the letters all lower case to accept multiple case strings.
print isPalindrome(inList)

著名的回文“A man a plan a canal panama”的输出是True。希望这会有所帮助!

【讨论】:

    【解决方案2】:

    您只需将其按空格分隔并再次加入:

    def isPalindrome(inString):
        inString = "".join(inString.split())
        return inString[::-1] == inString
    

    【讨论】:

      【解决方案3】:

      略有不同的方法。只需删除空格:

      def isPalindrome(inString):
          inString = inString.replace(" ", "")
          return inString == inString[::-1]
      

      【讨论】:

        猜你喜欢
        • 2021-02-25
        • 2013-09-27
        • 1970-01-01
        • 2010-10-31
        • 1970-01-01
        • 2021-05-10
        • 2019-02-12
        • 2014-02-23
        • 1970-01-01
        相关资源
        最近更新 更多