'Why my code palindrome works only for single input not for many inputs?
A palindrome is a word or a phrase that is the same when read both forward and backward. Examples are: "bob," "sees," or "never odd or even" (ignoring spaces). Write a program whose input is a word or phrase, and that outputs whether the input is a palindrome.
I'm only getting this half right. my code is working for bob, and sees. When an input is "never odd or even" my code doesn't work it shows is not a palindrome but it should be a palindrome.
What am I doing wrong here?
word = str(input())
new = word.replace(" ", "")
new = new[::-1]
if word == new:
print('{} is a palindrome'.format(word))
else:
print('{} is not a palindrome'.format(word))
Solution 1:[1]
You are comparing word with new, but to generate new you had removed all the spaces.
Solution 2:[2]
That is because of line new = word.replace(" ", "") - the word is kept with the spaces in it. You should make a version of word with no spaces, reverse that, then compare it with the no-spaces word.
Something like:
word = str(input())
spaceless_word = word.replace(" ", "")
new = spaceless_word[::-1]
if spaceless_word == new:
print('{} is a palindrome'.format(word))
else:
print('{} is not a palindrome'.format(word))
Solution 3:[3]
try this
word = str(input())
word = word.replace(" ", "")
new = word
new = new[::-1]
if word == new:
print('{} is a palindrome'.format(word))
else:
print('{} is not a palindrome'.format(word))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bnz |
| Solution 2 | foobarna |
| Solution 3 | Strider |
