Python Shorts — Reverse a String

John Clark Craig
3 min readMay 8, 2022

A series of short Python programming examples. Today we’ll reverse the order of the characters in a string.

Arrows pointing both ways, left and right.
Photo by 愚木混株 cdd20 on Unsplash

There’s no string reverse function in Python, but it’s very easy to get this done in several ways.

reversed()

Any iterable object in Python can be reversed by passing it to the reversed() function. The result is an iterable object of type “reversed”. That sounds complicated, and it’s not at all obvious what can we do with an instance of the “reversed” class.

s = "This is a string"x = reversed(s)
print(type(x))
# <class 'reversed'>

The trick is to use join() to stick all the reversed pieces together again. Here’s how we can reverse a string in one line of code.

s = "This is a string"r = "".join(reversed(s))
print(r)
# gnirts a si sihT

The pieces (characters) of the reversed object are joined together, separated by empty strings, and voila!, out pops a reversed string.

A Better Way

There’s an even better way to reverse a string. Follow along with this example and it will become clear.

# reverse_string.py

--

--

John Clark Craig
John Clark Craig

Written by John Clark Craig

Author, inventor, entrepreneur — passionate about alternate energy, technology, and how Python programming can help you hack your life.