Search code examples
pythonstringpalindrome

Palindrome in Python operating on strings only


I am trying to write a program in Python which will detect that the word given by a user is a palindrome or not.

Here is my code - I operate only on strings - my solution is totally different that other which I have seen here or anywhere, thus I would like you - StactOverFlow users ;) - to check its correctness.

I needn't say that I am not a pro, having rather basic knowledge. However, I would be glad if anyone spend their time and give me some feedback.

# a palindrome
string = input('word: ')
if(len(string) % 2 != 0):
  left = string.lower()[0:int((len(string)-1)/2)]
  right = string.lower()[int((len(string)-1)/2 + 1): ]
  if left == right[::-1]:
    print('{} is a palindrome'.format(string.lower()))
  else:
    print('{} is not a palindrome'.format(string))
else:
  left = string.lower()[0:int((len(string)/2))]
  right = string.lower()[int(len(string)/2):]
  if left == right[::-1]:
    print('{} is a palindrome'.format(string.lower()))
  else:
    print('{} is not a palindrome'.format(string.lower()))

Solution

  • To detect a palindrome just check if the reverse string is equal to the original one

    palindromes_test = ['ABCDCBA','EVE','ABCABC']
    
    print ([v for v in palindromes_test if (v == (v[::-1]))])
    

    output

     ['ABCDCBA', 'EVE']