Python Forum

Full Version: Simple Palindrome
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi. I have simple program which checks if a string is a palindrome
def is_palindrome(i):
   if len(i) <= 1:
       return True
   else:
       if i[0] != i[len(i)-1]:
           return False
       else:
           return is_palindrome(i[1:len(i)-1])
print(is_palindrome("kajak"))
Unfortunately, when I write a word with a capital letter the result is "false". Please help. What to do and what to add to my code so that the same text in upper or lower case will be considered "True"?
One easy method is to convert your string to all lower case, then run the palindrome check on the converted string.
>>> s = "MixedCase"
>>> s = s.lower()
>>> print(s)
mixedcase
Thanks! All the code looks like this:
s = "Kajak kajak"
s = s.lower()

def is_palindrome(i):
   if len(i) <= 1:
       return True
   else:
       if i[0] != i[len(i)-1]:
           return False
       else:
           return is_palindrome(i[1:len(i)-1])
print(is_palindrome(s))
reverse string works good to reduce iterations,

def is_palindrome(i):
    if len(i) <= 1 or i.lower() == i[::-1].lower():
        return True
    else:
        return False
 
print(is_palindrome("kaJAK"))
Best Regards,
Sandeep.

GANGA SANDEEP KUMAR
It always good to have common understanding of terms (supposedly Socrates has said "The beginning of wisdom is the definition of terms.").

Palindrome according to Wikipedia:

Quote:A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam, racecar.
/.../
Sentence-length palindromes ignore capitalization, punctuation, and word boundaries.

So maybe it's a good idea to check whether code recognizes palindromes like "Madam, I'm Adam" and "Never odd or even"