简体   繁体   中英

How do I handle Palindrome with spaces in python?

I'm trying to check if a string is palindrome in python using deque. But the code below just checks a string with no space, how can I adjust it to a code which handles strings with spaces as well? eg: It only works if I write the input as "BORROWORROB" but not when it's "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)))

You have to remove white spaces before starting the logic of the function:

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM