回文函数 Python

Palindrome Function Python

我正在尝试编写一个函数来判断输入的单词或短语是否为回文。到目前为止,我的代码有效,但仅适用于单个单词。如果我输入带有 space 的内容,例如 'race car' 或 'live not on evil',该函数将如何 return 为真?此页面上的其他问题解释了如何用一个词而不是多个词和 spaces 来做到这一点。这是我到目前为止的...

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)

您只需要将其按空格拆分并再次加入即可:

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

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

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。希望这对您有所帮助!

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

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