Find Palindrome Strings
Let’s think about what you need to check in order to see if a word is a palindrome or not. You’re going to have to see if the reverse version of the string is the same as its normal version. Luckily, Python has a built-in function for this:
Here you go. You got Python reversed. Another thing you’ll have to pay attention to is that Python strings are case-sensitive. So
"Ana" with the capital A is not the same as
"ana" with a lowercase a.
As you can see, you get
'ana' with every character lowercased. Okay, you’re ready. Time to find palindrome strings. Let’s create a predicate function named
is_palindrome to get
word as an input.
It should return
True if a string is a palindrome and
False if not. To do that, let’s reverse the input word using the
reversed() function and store it in a variable named
word as the input. Okay, now let’s write up what your function should return.
We expect it to be
False, and it is
False. It works, perfect! So for a palindrome string such as
"Ana", it returned
True, and for a non-palindrome word—for example,
False. So it works great. Now let’s use
is_palindrome as the function argument and
words as the iterable. It returned
['Ana', 'madam', 'racecar'] as a result, which is perfect. These are the only palindrome words inside of the tuple
Become a Member to join the conversation.