Although it may not be a common thing to do in any real-world scenario, reversing strings is a pretty common operation you'll face in a job interview. Especially if you are applying for a job in a programming language that doesn't have built-in methods for reversing strings. By asking you to reverse a string, an interviewer can get a pretty accurate impression of how you approach analyzing the problem and building a solution from scratch.
Also, since there can be plenty of solutions for this problem, this is your chance to shine and show your awareness of the different execution speeds between different algorithms, thus create the best possible solution.
In this article, we'll take a look at how to reverse a string in Python. We'll consider several possible solutions and compare them, so you can choose the one that best fits your needs.
Obviously, interviews aren't the only place where you can face the need to reverse a string - for example, there are some regular expression problems that are solved much easier when working with reversed strings.
Strings in Python
String in Python is an immutable array of bytes - more specifically a sequence of bytes representing Unicode characters. Actually, a string is written in code as a sequence of characters surrounded by a pair of quotation marks (single or double), but they are internally stored as a sequence of Unicode codes:
example_str = "Hello World!" # The same as: # example_str = 'Hello World!'
Note: The actual object used to deal with strings in Python is called the
str object. It essentially represents a string data type.
One important characteristic of strings in Python is that they are immutable, meaning that they can't be modified after they were created. The only way to modify a string would be to create its modified copy, which complicates many operations on strings. It's no different for the one of our particular interest in this article - the operation of reversing a string.
Reversing a String in Python
Now that we've covered all the basics, we can look at how to actually reverse a string in Python. As we've stated before, there are several ways you can do that - in this article, we'll cover some of the most used. Each approach has its own strengths and weaknesses, some are more efficient but less readable. On the other hand, some are really readable and easy to understand, but at the cost of being not that efficient.
In the following sections we'll be reversing the string
"Hello World!", which should be reversed to the
example_str = "Hello World!"
Recommended Solution: Using the Slice Notation
Another important property of strings in Python is that they are sliceable. That means a substring can be extracted from the original string - and Python offers a pretty straightforward way to do that using the slice operator.
Note: If you'd like to learn more about slicing strings in Python, you should read the article "Python: Slice Notation on Strings"
The slicing operator in Python has the following syntax -
[start:end:step]. It extracts a substring starting from the
start to the
end. If the
step is a positive number, the
start must be less than the
end, therefore the slicing operator creates a substring moving forwards. On the other hand, if
step is a negative number, the substring is created going backward in the original string. Therefore, if you set the
-1 and leave
end blank, you will effectively reverse a whole string:
example_str = "Hello World!" reversed_str = example_str[::-1] print(reversed_str)
We've used the slicing operator on our
example_str in the previously described way, which will yield us the reversed version of our original string:
This approach to reversing a string in Python is considered to be the most efficient for the large input strings, but that comes at the cost of poor readability - especially for those who are not familiar with the slicing notation in Python. To improve that, we can wrap the slicing in a function, which will increase the readability of the final code:
def reverse_string(s): return s[::-1]
Later, we'd use this function instead of the plain slicing operator to reverse desired string, and the resulting string will be the same as before -
reversed_str = reverse_string(example_str)
Advice: Wrapping each section of a code in a function is generally a good practice! Besides improving the code readability it actually helps you create more modular and reusable code. Therefore, you can wrap each of the following code snippets in the function in the same manner as shown in this section.
Using join() and reversed()
Although the slicing performs the best in terms of speed, the solid alternative in terms of readability is to combine two built-in Python methods -
First of all,
reversed() returns a reversed iterator for the string passed as its argument. That enables us to go over the original string backward and append its characters to the empty string using
example_str = "Hello World!" reversed_str = ''.join(reversed(example_str)) print(reversed_str)
This will create a reversed copy of the original string:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Note: If you are not familiar with the concept of iterators in Python - you should read "Introduction to Python Iterators"
Using a for Loop
Loops can also be used to reverse a string in Python - the first one we'll consider is the
for loop. We can use it to iterate over the original string both ways - forwards and backward. Since we want to reverse a string, the first thing that comes to mind is to iterate over the string from the end to the start and append each character to the new string. For that purpose, we'll use the
example_str = "Hello World!" reversed_str = "" for i in reversed(example_str): reversed_str += i print(reversed_str)
We've iterated backward over the original string and appended each character to the
resulting_str, which will store the reversed version of the
example_str in the end:
Note: Notice how we've been adding each character to the reversed string, but strings in Python are immutable. We can do that because Python, essentially, creates a modified copy of a string each time we append a character to it, before solidifying the result as an immutable string and returning it.
An alternative approach is to iterate over the original string forwards, from the start to the end, and create the reversed version of the original string in the loop itself:
example_str = "Hello World!" reversed_str = "" for i in example_str: reversed_str = i + reversed_str print(reversed_str)
This will give us the same result as using the reversed iterator in the loop.
Using a while Loop
Another loop we can use to reverse a string is the
while loop. This approach is a bit more complicated than others, but can give you a great insight in how reversing string works on a lower level:
example_str = "Hello World!" reversed_str = "" i = len(example_str) - 1 while i >= 0: reversed_str += example_str[i] i -= 1 print(reversed_str)
Which will result in:
As we've seen in this article, there are plenty of approaches on how to reverse a string in Python, and each of them has its strengths and weaknesses. Generally speaking, the one way you should choose for the most time is the slicing operator - it is the most efficient and the most Pythonic way to reverse a string. Other approaches are less efficient, therefore, think twice before using them if the execution speed is crucial in your code.