How to Reverse a String in Python

Introduction

Before we begin talking about how to reverse a string in Python, let's briefly understand – What is Python?

Python is a versatile and popular programming language used for various applications. It is easy to learn, making it ideal for beginners and experts alike. Python's clear and concise syntax enables efficient coding, saving time and effort.

From web development to data analysis and artificial intelligence, Python provides extensive libraries and frameworks. Its versatility, simplicity, and large user community make Python an excellent choice for anyone wanting to dive into the world of programming.

In this tutorial, you will reverse a string in Python. We will also address a few FAQs on how to reverse a string in Python.

Advantages of Python

  1. Versatility: Python is a multipurpose language renowned for its wide range of applications in web development, data analysis, AI, and more.
  2. Easy to learn: Python's simple syntax and readability make it beginner-friendly.
  3. Time-efficient: Python's concise coding style allows developers to write programs faster, increasing productivity.
  4. Extensive libraries: Python offers numerous libraries and frameworks that simplify complex tasks and accelerate development.
  5. Strong community: Python has a large and supportive user community, providing ample resources and solutions to programming challenges.

In Python, a string is a sequence of Unicode characters. Python supports many functions for string manipulation, but there are no built-in functions or methods explicitly designed to reverse strings.

>>> 'VegaStack'.reverse()
Output

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, but is commonly used when coding interviews.

This tutorial describes various ways to reverse strings in Python.

Using Slicing

Understanding how indexing works in Python is important for performing string slicing operations. Index numbers are commonly used to access a particular character in a string.

There are two types of indexing. Positive and negative indexes.

The character A can be accessed with either positive index number 3 or negative index number -6.

>>> print('VEGASTACK'[3])
Output

A
>>> print('VEGASTACK'[-6])
Output

A

You can use the slicing technique to get a set of characters from a string. Slicing is an operation that extracts a sequence of substrings from a specified string.  

Slice-Syntax:

string[start:stop:step]
  • The first argument specifies the index at which to start the extraction. If a negative index is used, specify the offset from the end of the string. If you omit this argument, the slice starts at index 0.  
  • The second argument specifies the index before stopping the extraction. The result does not contain a stop element. If a negative index is used, specify the offset from the end of the string. If this argument is omitted or greater than the length of the string, the slice will be moved to the end of the string.  
  • The third argument is optional and specifies the slice step. If the step argument is not used, it defaults to 1. If a negative value is used, the slice will take the elements in reverse order.

As a result of splitting the string, a new string containing the extracted elements is created and the original string is unchanged.

To use slices to invert a string, omit the start and stop arguments and use a negative step increment of -1.

A negative step increment of -1 means that the slice starts at the last element and ends at the first element, resulting in the reverse of the string.

>>> print('VEGASTACK'[::-1])
Output

KCATSAGEV

You can also define a user-defined function and use it to invert the string.

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

INPUT_STRING = "VEGASTACK"

if __name__ == '__main__':
    print("INPUT STRING -", INPUT_STRING)
    print("REVERSED STRING -", rev_str_thru_slicing(INPUT_STRING))
Output

Input String - VEGASTACK
Reversed String using Slicing - KCATSAGEV

Using reversed() Function

The built-in reserve() function processes the string elements in reverse order and returns a reverse iterator.

In the example below, the elements of the reverse iterator are concatenated into an empty string using the join() operator:

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

INPUT_STRING = "VEGASTACK" 

if __name__ == '__main__':

    print("INPUT STRING -", INPUT_STRING)
    print("RESERVED STRING THROUGH JOIN & REVERSED", rev_str_thru_join_revd(INPUT_STRING))
Output

Input String - VEGASTACK
Reserved String Through Join & Reserved Methods - KCATSAGEV

Using List reverse()

To reverse a string using the list reverse() method,  the string must first be converted to a list using the list constructor. Then the list items are reversed using the reverse() method, and finally the list items are concatenated into a string using the join() method.

Here is an example:

def rev_str_thru_list_reverse(STR):
    lst = list(STR)
    lst.reverse()
    return(''.join(lst))
 
INPUT_STRING = "VEGASTACK"
 
if __name__ == '__main__':
    print("Input String -", INPUT_STRING)

print("Reserved String Through List", rev_str_thru_list_reverse(INPUT_STRING))
Output

Input String - VEGASTACK
Reserved String Through List Reverse Method - KCATSAGEV

Using Recursive Function

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

In the code, below, the function rev_str_thru_recursion is called until the length of the string is greater than 0. On each call, the string is truncated, leaving only the first character. It is then concatenated with the trimmed characters.

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

INPUT_STRING = "VEGASTACK"

if __name__ == '__main__':
    print("INPUT STRING -", INPUT_STRING)

print("RESERVED STRING THROUGH RECURSION", rev_str_thru_recursion(INPUT_STRING))

Comparative Analysis

In this section, we will make a simple comparison between these four identified methods to determine their effectiveness. We will analyze the performance using a Python module called "timeit".

It provides the time required for the code to run. The "repeat" option of the "timeit" module makes it possible to repeat code execution millions of times. We can interpret the output as the average time taken by running the code a million times.

 

The table above shows that the slicing method is seven times faster than the Reverse List method, 7.5 times faster than the Join & Reserved method, and 83 times faster than the Recursion method. So Slicing is the fastest and best way to reverse a 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)

FAQs to Reverse a String in Python

Does Python provide any built-in function for string reversal? 

Yes, Python offers the built-in reversed() function. It returns an iterator that produces the characters in reverse order.

Can I reverse a string in-place without using extra memory? 

No, strings in Python are immutable, meaning they cannot be changed once created. So, reversing a string in-place is not possible. You would need to create a new reversed string variable.

How do I handle Unicode characters when reversing a string? 

Python handles Unicode characters seamlessly. The slice notation and reversed() function can handle strings with Unicode characters, maintaining the correct order.

Can I reverse a string that contains whitespace or special characters? 

Yes, you can reverse strings that contain whitespace or special characters without any issues. The reversal method works for all characters in the string.

Are there any performance concerns when reversing long strings? 

Reversing a long string using the slice notation or reversed() function has a time complexity of O(n), where n is the length of the string. Performance should not be a concern, even for longer strings.

Does reversing a string change the original string? 

No, reversing a string will not modify the original string. Instead, it will create and return a new reversed string.

Can I reverse individual words in a sentence using the same method? 

No, the slice notation or reversed() function alone cannot reverse individual words in a sentence. You would need to split the sentence into words, reverse each word, and then join them back together.

Conclusion

Python does not have built-in functions to reverse a string, but we can use other methods to reverse a string. Regression test analysis shows that slicing method is the fastest way to reverse a string.

If you have any queries, please leave a comment below and we’ll be happy to respond to them.