Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Palindrome Porgram

Hello, I am doing some extra exercises to practice and I made this a program that checks if a word or sentence is a palindrome. I got it working but I don't know how to make it so that it can check words with spaces. For example "racecar" works but not "race car" this is my code:

palindrome = input("Please write a setence: ")
reverse = palindrome[::-1]
if reverse in palindrome:
    print("It's a palindrome!")
else:
    print("Sorry not a palindrome.")

If anyone can help me or point me in the right direction I would apperciate it. Thank you!

1 Answer

You just need to remove the spaces in your comparison: "racecar".replace(" ","") will be the same as "race car".replace(" ","")[::-1]. Also as a side node, your code does work but I find it reads a little bit better if you replace your in with the equality == operator, because after all you are checking if one thing is equals the other reversed and not if it's in the other.

Hello, Thank you for your reply. I changed the in to ==. Thank you for that. I used the .replace and it worked but only for two word palindromes. I will keep researching .replace so I can figure out who to do it with different size senteces. Thanks for your time!

Happy to help! Also keep in mind that if someone writes uppercase/lowercase such as: "Lol" it's going to be different than the reverse "loL". You might want to use .lower()/.upper()/.casefold() for your comparisons for them to evaluate correctly. If you want you can share that example that you mentioned it doesn't work.

Hello Pedro,

Here is the code I have so far. I added a while loop and the .lower you suggested. It's workin fine for two words like race car but if I put in something like 'was it a cat i saw' it still says its not a palindrome but if I type it without spaces then it passes. Thank so much fro taking the time to help me out.

while True:
    palindrome = input("Please write a setence: ".lower())
    reverse = palindrome[::-1]
    if palindrome.lower() == 'quit':
        break
    elif reverse.replace(" ","") == palindrome.replace(" ",""):
        print("It's a palindrome!")
    else:
        reverse != palindrome
        print("Sorry not a palindrome.")

print("Thank you for playing!")