I've just started Python and need to write a program that tells if a string is a palindrome. Here is what I have so far.

def palp(word):
    if len(word) < 2:
        return True
    left_index =  (0)
    right_index = len(word) - 1
    while len(left_index) <> len(right_index):
        return False
    if left_index == right_index:
        left_index + 1
        right_index - 1
        return True

I don't know but for some reason it doesn't return true for any palindrome except for ones with only one letter.

Recommended Answers

All 4 Replies

You can not take len of integer values, wouldn't you need to check letters in word? You also forgot CODE tags.

def palindromic(s):
    return True if str(s) == str(s)[::-1] else False

Unnecessary complicated, but forgetting case of word differences.

This simple version, which does not deal with palindromic sentences:

def palindromic(s):
    s = s.lower()
    return s == s[::-1]
>>> palindromic('Saippuakivikauppias')

As pyTony say you complicated it by use of ternary operator( a if b else c )
One thing also to remember is to remove punctuation.
Here one with translate.

from string import punctuation

def is_palindrom(word):
    word = word.lower().translate(None, punctuation)
    return word == word[::-1]

print is_palindrom('Saippuakivikauppias') #True

And a test with a longer palindromic sentence.

def is_palindrome(s):
    letters = [c for c in s.lower() if c.isalpha()]
    return letters == letters[::-1]

s = '''\
A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe,
percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again
(or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats,
a peon, a canal ? Panama!'''

print is_palindrome(s) #True
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.