如何处理 python 中带空格的回文?

How do I handle Palindrome with spaces in python?

我正在尝试使用双端队列检查 python 中的字符串是否为回文。但是下面的代码只是检查一个没有 space 的字符串,我怎样才能将它调整为处理带有 space 的字符串的代码呢?例如:它仅在我将输入写为“BORROWORROB”时有效,但在输入为“BORROW OR ROB”时无效

from pythonds.basic import Deque
def isPalindrome(word):
    if word is None:
        return False
    if len(word) <= 1:
       return True

    DQ = Deque()
    for w in word:
        DQ.addRear(w)

    while (DQ.size() > 1):
        front = DQ.removeFront()
        rear = DQ.removeRear()
        if front != rear:
            return False
    return True


def readInput():
    inp = input("Enter string: ")
    return inp

word = readInput()
print ("Is \"{}\" a palindrome: {}".format(word, isPalindrome(word)))

您必须在开始函数逻辑之前删除空格:

from pythonds.basic import Deque
def isPalindrome(word):
    word = word.replace(" ", "")
    if word is None:
        return False
    if len(word) <= 1:
       return True

    DQ = Deque()
    for w in word:
        DQ.addRear(w)

    while (DQ.size() > 1):
        front = DQ.removeFront()
        rear = DQ.removeRear()
        if front != rear:
            return False
    return True


def readInput():
    inp = input("Enter string: ")
    return inp

word = readInput()
print ("Is \"{}\" a palindrome: {}".format(word, isPalindrome(word)))