How to Reverse a String in Python
5 min read•
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.
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.
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.
You can access the character
n, either through a positive index number of
2 or through a negative index number of
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.
- 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
stopelement. 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
stepargument 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
stop arguments and use a negative step increment of
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.
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("INPUT STRING -", INPUT_STRING) print("REVERSED STRING -", rev_str_thru_slicing(INPUT_STRING))
Input String - Linuxize Reversed String using Slicing - ezixuniL
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
def rev_str_thru_join_revd(STR): return "".join(reversed(STR)) INPUT_STRING = "Linuxize" if __name__ == '__main__': print("INPUT STRING -", INPUT_STRING) print("RESERVED STRING THROUGH JOIN & REVERSED", rev_str_thru_join_revd(INPUT_STRING))
Input String - Linuxize Reserved String Through Join & Reserved Methods - ezixuniL
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
Here is an example:
def rev_str_thru_list_reverse(STR): lst = list(STR) lst.reverse() return(''.join(lst)) 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 else: return rev_str_thru_recursion(STR[1:]) + STR INPUT_STRING = "Linuxize" if __name__ == '__main__': print("INPUT STRING -", INPUT_STRING) print("RESERVED STRING THROUGH RECURSION", rev_str_thru_recursion(INPUT_STRING))
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.
|Methods||Execution Time||Comparison Ratio Calc.|
|Join & Reserved||1.73||7.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.
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) print(min(SLICING_PERF), mean(SLICING_PERF), max(SLICING_PERF), SLICING_PERF) 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
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.