How to Reverse a String in Python

Published on

5 min read


Sriram Ramanujam
Python Reverse String

In Python, a string is a sequence of Unicode characters. Though Python supports numerous functions for string manipulation, it doesn’t have an inbuilt function or method explicitly designed to reverse the string.

>>> 'Linuxize'.reverse()
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'str' object has no attribute 'reverse'

String reversal is not a common operation in programming and is generally used is in coding interviews.

This article goes through several different ways to reverse a string in Python.

Using Slicing

Understanding how indexing works in Python is crucial for performing the String Slice operation. Generally, Index numbers are used to access specific characters within a string.

There are two types of indexing; positive and negative indexing.

Using Slicing

You can access the character n, either through a positive index number of 2 or through a negative index number of -6:

>>> print('Linuxize'[2])
>>> print('Linuxize'[-6])

We can call out a range of characters from a string through a slicing technique. Slicing is the operation that extracts the sequence of a substring from the given string.

Slice Syntax:

  • The first argument specifies the index at which the extraction begins. When a negative index is used, it indicates an offset from the end of the string. If this argument is omitted, slicing starts from index 0.
  • The second argument specifies the index before which to end extraction; the result doesn’t include the stop element. When a negative index is used, it indicates an offset from the end of the string. If this argument is omitted or greater than the length of the string, slicing goes to the end of the string.
  • The third argument is optional and specifies the step of the slicing. When the step argument is not used, it defaults to 1. When a negative value is used, the slice takes elements in reverse order.

The result of slicing a string is a new string containing the extracted elements, and the original string is not modified.

To reverse a string using slicing, omit the start and stop arguments and use a negative step increment of -1.

The negative step increment of -1 means that the slicing starts at the last element and ends at the first element, resulting in a reversed string.

>>> print('Linuxize'[::-1])

You can also define a custom function and use it to reverse strings:

def rev_str_thru_slicing(str_):
    return str_[::-1]

INPUT_STRING = "Linuxize"

if __name__ == '__main__':
    print("REVERSED STRING -", rev_str_thru_slicing(INPUT_STRING))
Input String - Linuxize
Reversed String using Slicing - ezixuniL

Using reversed() Function

The built-in reserved() function process the string items in reverse order and returns a reversed iterator.

In the example below, the reversed iterator’s elements are added to an empty string using the join() operator:

def rev_str_thru_join_revd(STR):
    return "".join(reversed(STR))	

INPUT_STRING = "Linuxize" 

if __name__ == '__main__':

    print("RESERVED STRING THROUGH JOIN & REVERSED", rev_str_thru_join_revd(INPUT_STRING))
Input String - Linuxize
Reserved String Through Join & Reserved Methods - ezixuniL

Using List reverse()

To reverse a string with the list reverse() method, first, the string needs to be converted to a list using the list constructor. Then the list items are reversed in place with the reverse() method, and finally, the list items are joined into a string using the join() method.

Here is an example:

def rev_str_thru_list_reverse(STR):
    lst = list(STR)
INPUT_STRING = "Linuxize"
if __name__ == '__main__':
    print("Input String -", INPUT_STRING)

print("Reserved String Through List", rev_str_thru_list_reverse(INPUT_STRING))
Input String - Linuxize
Reserved String Through List Reverse Method - ezixuniL

Using Recursive Function

In Python, a recursive function is a function that calls itself until some condition is met.

In the code snippet below, the rev_str_thru_recursion function calls itself until the string length is greater than zero. On each call, the string is sliced, leaving only the first character. Later on, it is concatenated with the sliced characters.

def rev_str_thru_recursion(STR):
    if len(STR) == 0:
         return STR
        return rev_str_thru_recursion(STR[1:]) + STR[0]

INPUT_STRING = "Linuxize"

if __name__ == '__main__':


Comparative Analysis

In this section, we’ll perform a simple comparison between these four defined methods to identify their efficiency. We’ll analyze the performance using a Python module called “timeit”. It provides the time taken for the execution of the code snippets. “repeat” option of the “timeit” module helps to repeat the code execution one million times. We can comprehend the output as an average time taken by executing the code snippet one million times.

MethodsExecution TimeComparison Ratio Calc.
List Reverse1.637x
Join & Reserved1.737.5x

The table above shows that the Slicing method is seven times faster than the List Reverse approach, 7.5 times faster than the Join & Reserved approach, and 83 times faster than the recursion approach. So Slicing is the quickest and best way to reverse the string.

Comparative Analysis
The above results are the comparative analysis of discussed methods to reverse the string in the same environment. Numbers might vary in different computing environments, but the ratio will probably remain the same.
if __name__ == "__main__":

    ## Performance Calculation

    import timeit
    from statistics import mean

    s = INPUT_STRING * 10
    repeatCount = 100

    SLICING_PERF = timeit.repeat(lambda: rev_str_thru_slicing(s), repeat=repeatCount)

    J_R_PERF = timeit.repeat(lambda: rev_str_thru_join_revd(s), repeat=repeatCount)
    print(min(J_R_PERF), mean(J_R_PERF), max(J_R_PERF), J_R_PERF)

    LIST_PERF = timeit.repeat(lambda: rev_str_thru_list_reverse(s), repeat=repeatCount)
    print(min(LIST_PERF), mean(LIST_PERF), max(LIST_PERF), LIST_PERF)

    RECUR_PERF = timeit.repeat(lambda: rev_str_thru_recursion(s), repeat=repeatCount)
    print(min(RECUR_PERF), mean(RECUR_PERF), max(RECUR_PERF), RECUR_PERF)


Python doesn’t have any built-in functions to reverse the string, but we can use other methodsto reverse the string. The regression test analysis showed that the slicing method is the fastest way to reverse a string.

About the authors

Sriram Ramanujam

A seasoned Global Network Automation Architect with 10+ years of rich industry experience in developing scalable solutions for network automation, engineering design, operation and telemetry.