Sign In
Sign In

How to Reverse a String in Python

How to Reverse a String in Python
Amr Essam
Technical writer
Python
10.10.2024
Reading time: 8 min

One of the top reasons for the popularity of Python is the extensive built-in capabilities it has. It offers a lot of modules and functions that enable developers to achieve specific tasks with simplicity. A very common example of these tasks is string manipulation.

String manipulation is the process in which we modify a string variable by applying some type of operation like concatenation, splitting, or reordering of the characters. This manipulation can be very handy in cases like text processing, data analysis, or problem solving.

In this article we’re going to cover one fundamental string manipulation operation, which is string reversal. We’ll explore different methods to reverse a string in Python and we’ll show an example for each one. We’ll also compare the efficiency between these different methods.

Reverse a String Using Slicing

Slicing is the process of extracting part of a sequence object (string, list, tuple, etc). We can specify the range of elements – from the start to the end – which we want to extract from the sequence. This range of elements, also called a slice, is then returned from the slicing operation and we can store it in another variable.

We can apply the slicing in Python in two different ways, using the slice() function, or with the slicing [::] operator.

The slice() Function

A slice() function takes three arguments which are the starting element, ending element, and a step. It returns a slice object which we can later use on our sequence to extract a part of it.

For example, we can slice a string with the following code:

my_string="ABCDEF"
my_slice=slice(2,5,1)
new_string=my_string[my_slice]
print(new_string)

In the above code, we have the original string which is my_string. We use the slice() function with parameters 2, 5, and 1. This means that we need to extract part of the string starting from index 2 until index 5, and moving 1 element at a time. 

Image10

Now let’s run this code and check the output:

Image6

As we can see, our new_string contains the sliced part which is CDE. It’s important to note that the slice begins with the starting index until the element before the ending index, but it doesn’t include the ending index itself.

We can also pick the slice in the opposite direction by using a negative value for the step. Meaning that we’ll start from the bigger index until the smaller one.

Image1

We can achieve this with the following code:

my_string="ABCDEF"
my_slice=slice(5,2,-1)
new_string=my_string[my_slice]
print(new_string)

If we run our code we should get the slice in a reversed order:

Image11

In the above image the new_string contains the elements starting from index 5 until index 2 in a reversed order.

Now in order to reverse the whole string, we can use the slice() function with a reverse order starting from the last index until the first index:

my_string="ABCDEF"
my_slice=slice(5,None,-1)
new_string=my_string[my_slice]
print(new_string)

In the above code, we start our slice from index 5 which is the final index in my_string, until the index None, which means the starting index including the element stored in it.

We should get a reversed string by running the above code:

Image7

The new_string now is the reversal of the original my_string.

The slicing[::] Operator

The slicing [::] operator works the same as the slice() function but provides a shorter and easier syntax. Instead of creating a slice object and pass it to the original string, we can merge these in a single step with the slicing operator:

my_string="ABCDEF"
new_string=my_string[5:None:-1]
print(new_string)

In the above example, we removed the slice() function and used the slicing operator directly on the string. We use the same parameters for the starting index, ending index, and the step:

Image2

We can see our string is reversed in the same way as the slice() function. We can also improve the syntax further by replacing the starting and ending index with empty value as follows:

my_string="ABCDEF"
new_string=my_string[::-1]
print(new_string)

This automatically translates to the beginning and the end of the string:

Image9

Again we get our string in a reversed order with a more elegant syntax.

Reverse a String Using the reversed() Function

The reversed() function is a Python built-in function that accepts an iterable as a parameter and returns an iterator in a reversed order. We can then iterate over the returned object and access its elements as we need.

For example, the following code will print the elements of the returned iterator after reversing a string:

iterable_string="ABCDEF"
my_iterator=reversed(iterable_string)
for element in my_iterator:
    print(element)

Now let’s run our code:

Image13

In the above image, we have each element in our string in a reversed order.

We can utilize the reversed() function to reverse a string by using it along with the join() function. The join() function is also a Python built-in function that takes an iterable object as a parameter, it concatenates the elements of this iterable and returns a string object as a result of concatenation.

Because every iterator is also an iterable, we can pass the iterator returned from the reversed() function as a parameter to the join() function:

iterable_string="ABCDEF"
my_iterator=reversed(iterable_string)
concat_string=''.join(my_iterator)
print(concat_string)

In the above code, we concatenate the elements of the my_iterator (which is basically the reverse of the iterable_string) using the join() function, and we save the returned string in the concat_string.

The empty string ' ' in the join() function decides the separator we want to include between our concatenated elements. Since we don’t need to separate the elements by any character we provided an empty string.

Let’s check the output of our code:

Image5

As we can see, the join() function converted our reversed iterator object into a string.

Reverse a String Using a Loop

If we want to reverse a string using the basic programming structures without utilizing a built-in function, we can achieve this with traditional Python for loop.

We can use the for loop to iterate over our string in the opposite direction from the last index to the first index. Through the iteration, we can pick the element at each index and concatenate it to another empty string:

my_string="ABCDEF"
reversed_string=''
for i in range(len(my_string)-1, -1, -1):
    reversed_string+=my_string[i]
print(reversed_string)

The len() function here is used to return the number of characters in my_string, by subtracting 1 from this number we get the last index in the string. So, the expression len(my_string)-1 will be evaluated to 5.

The range() function will then return a sequence of numbers starting at 5, and decremented by 1 until it reaches 0, which is specified by the -1 and -1 parameters.

At each iteration, the character at the specified index will be appended to the reversed_string. Let’s run this code and check the result:

Image8

We can see the reversed_string was created by concatenating the characters from my_string in the opposite direction.

Reverse a String Using Recursion

Recursion is the process where a function calls itself. This can be beneficial if we want to repeat the same operation multiple times until we reach a specific condition, called a base case.

To reverse a string, we can create a recursive function that takes the string as a parameter and returns a call to the same function with a substring parameter removing the first character and appending it to the end.

Image4

This process continues until the substring passed to the function has a length of 1.

We can implement this using the following code:

def reverse_string(my_string):
  if len(my_string) <= 1:
    return my_string
  return reverse_string(my_string[1:]) + my_string[0]

ordered_string="ABCDEF"
reversed_string=reverse_string(ordered_string)
print(reversed_string)

Now let’s run our code:

Image12

And we get our reversed string after recursively calling the function which removes the first element and appends it to the end of the string.

Reverse a String Using List Comprehension

List comprehension provides an easy syntax to create a new list out of an existing list. We can utilize this to reverse a string in two steps, first we’ll create a new reversed list using the list comprehension, then we’ll concatenate the elements of this reversed list using the join() function:

my_string="ABCDEF"
reversed_list=[my_string[i] for i in range(len(my_string)-1, -1, -1)]
reversed_string=''.join(reversed_list)
print(reversed_string)

In the above code, we’re again using the range(len(my_string)-1, -1, -1) expression as in the for loop scenario to iterate over our string in a reversed direction. However, this time instead of appending the element in the index directly to a new string, we’re creating a new list out of the elements.

Once we get our reversed list, we pass it to the join() function to return a string from the concatenated elements of the list.

Let’s run our code:

Image3

We can see our string is reversed by creating a new reversed list and concatenating its elements.

Comparing the Efficiency of Each Method

Besides the difference in simplicity for each method, we also need to consider their performance in terms of the execution time.

We can measure the execution time for each method by using the time() function. The time() function is part of the time module and it returns the current time in seconds.

We can simply add the time() function at the beginning and at the end of the code that we want to measure, then we subtract both values.

Let’s apply this to some of the previous methods and compare the results:

Image14

Here we compared the slicing method with the list comprehension method, and we can see that the slicing method is more efficient by taking less execution time.

Conclusion

Python offers great control for programmers when it comes to string manipulation. It provides built-in modules and functions that support a wide range of use cases from text processing to data analysis. In this article, we covered a common string manipulation task which is string reversal. We explored some of the methods for reversing a string in Python including slicing, recursion, for loops, and list comprehension.

Python
10.10.2024
Reading time: 8 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us