How To Reverse a String in Python. Learn two methods and find out which is fastest
A string is a sequence of character data. We commonly refer to it as text data. Additionally, strings are iterables, which are enumerables—a data type that can be counted over—that have a structured order as well. Reversing a string means taking the last character and making it the first, second to last becomes second, etc.
Here’s a quick visual example:
name = "Jonathan"
# name in reverse => "nahtanoJ"
So, how do we reverse a string? There are two ways that I’ll cover.
This method involves treating the string as an array of characters, reversing it, and reconstituting it as a string. In other languages, this technique might involve a for
loop to iterate over each index and create a reversed data set. The next step is to take the array and recombine it as a string.
Here’s a JavaScript example to show how this looks within a traditional for
loop.
var name = "Jonathan";
var arr = [];
for(var i=name.length-1; i >= 0; i--) {
arr.push(name[i]);
}
var flipped = arr.join("");
console.log(flipped); // nahtanoJ
What we do here is begin at the highest index and manually count down, populating an array with each character. Finally, we join the array with an empty string as a delimiter, meaning the characters are sequential with nothing between them.
In Python, we don’t have traditional for
loops. It could be recreated using a while
loop, but we’re not going to go that route. Instead, we’ll use the reversed()
function to return a reverse iterator that will be similarly joined by empty strings.
name = "Jonathan"
reversed = "".join(reversed(name))
print(reversed) # nahtanoJ
Notice that .join()
is a member of the string class in the Python implementation.
Slice notation is a technique unique to Python that allows a shorthand notation within an iterable’s square brackets, which then executes a traditional slice.
Slice notation involves two colons and up to three values within the square brackets. The first, middle, and end values—separated by colons—are as follows: [start:stop:step]
By omitting the start and stop positions while passing -1
as the step value, we instruct Python to slice counting backwards and not to stop before the end of the string.
name = "Jonathan"
print(name[::-1]) # nahtanoJ
According to Dan Bader, slice notation is up to seven times faster than the reverse/join technique!
I replicated his test scenarios and yielded similar, but not as dramatic results.
import timeit
def reverse_join(s):
return "".join(reversed(s))
def slice_notation(s):
return s[::-1]
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
reverse_join_times = timeit.repeat(lambda: reverse_join(s))
slice_notation_times = timeit.repeat(lambda: slice_notation(s))
avg_reverse = sum(reverse_join_times)/len(reverse_join_times)
avg_slice = sum(slice_notation_times)/len(slice_notation_times)
print(avg_reverse) # 1.8536329854000002
print(avg_slice) # 0.38605856120000015
print(avg_reverse / avg_slice) # 4.801429554206191
Do you have another way of reversing a string? Share it and any other thoughts or insights in the comments below!
Thank you for reading !
#Python #Data Science #Development