Python Shorts — Reverse a String
A series of short Python programming examples. Today we’ll reverse the order of the characters in a string.
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