0
word = input("Enter a word:")
a = word[::-1]
print (a)

if a == word:
    print ("The entered word is a palindrome.")
if a != word:
    print ("The entered word is not a palindrome.")

This is my current code to see if a word is a palindrome or not. A palindrome is a word that is written the same backwards/forwards. e.g mum and dad, hannah etc.

How would I change this so that I can use it for a phrase also? e.g a phrase could be : "Lisa Bonet ate no basil"

However, with the code I have it wouldn't recognise the sentence as a palindrome. What do I need to do to fix that?

Chad S.
  • 6,252
  • 15
  • 25
  • Remove punctuation and whitespace from `word`? – vaultah Jan 04 '16 at 17:05
  • if I used the sentence "sit on a potato pan otis" the program still says it isn't a palindrome – potatomeister Jan 04 '16 at 17:06
  • You're looking at removing spaces, not punctuation, although the effect would be the same. This is a common programming problem. See http://stackoverflow.com/questions/8270092/python-remove-all-whitespace-in-a-string – Kinsa Jan 04 '16 at 17:08

1 Answers1

0

Use string.punctuation:

import string
p = string.punctuation
s = "Lisa Bonet ate no basil"
word = ''.join([x for x in s.lower() if not x in p]).replace(' ','') ## 'lisabonetatenobasil'

## Your logic here

You want to remove all the whitespace (hence .replace(' ','')) and you also want to standardize case (hence .lower()) for palindromes.

TayTay
  • 6,882
  • 4
  • 44
  • 65