Skip to content
Home » How To Reverse a String in Python

How To Reverse a String in Python

Spread the love

Sometimes you may need to reverse a string. How to do it in Python?

reverse a string

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.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version:


Spread the love

Leave a Reply