Spread the love
Sometimes you may need to reverse a string. How to do it in Python?
To reverse a string all we need is the slice operator with the step set to -1. Have a look:
>>> text = "I like music."
>>> rtext = text[::-1]
>>> rtext
'.cisum ekil I'
Let’s write a function that tests if a string is a palindrome. It is if it reads the same in both directions, like “gig” or “kayak”. You can neglect capitalization and white spaces:
def is_palindrome(text):
text_lowercase = text.lower() # set all characters to lowercase
text_no_spaces = "".join(text_lowercase.split()) # remove spaces
if text_no_spaces == text_no_spaces[::-1]:
print(f"'{text}' is a palindrome.")
else:
print(f"'{text}' is not a palindrome.")
is_palindrome("hello")
is_palindrome("A Santa at Nasa")
Output:
'hello' is not a palindrome.
'A Santa at Nasa' is a palindrome.
As you can see, there’s no magic involved. If you want to play with this function a bit more, here are some palindromes that you can test. They should all give you a positive result:
deed, radar, level, civic, racecar
I’m sure you can come up with some more of your own.
Here’s the video version:
Spread the love