How to Reverse a String in Python

How to Reverse a String in Python

02 Feb 2025
Beginner
39 Views
9 min read
Learn with an interactive course and practical hands-on labs

Free DSA Online Course with Certification

What is Reversing a String?

Reversing a string means changing the order of its characters so that the last character becomes the first, and the second last becomes the second as shown below.

reverse strings in Python

Reversing a string is a common operation in Python and is used in various applications such as data manipulation, text processing, and algorithm challenges. If you are preparing for a Python interview I am sure you are gonna face this question during the interview process.

Hence, In this Python Tutorial, we will learn how to reverse a string in Python using slicing, loops, and built-in functions. In short, we will explore multiple methods with examples to reverse strings in Python efficiently. This article is perfectly packed for Python beginners and Python coding interviews who want to practice, so stay tuned.

5 Ways to Reverse a String in Python

  1. Using Slicing ([::-1]): Slicing is the most efficient method to reverse a string in Python.
  2. Using a Loop: Iterates through the string and prepends characters to build the reversed string
  3. Using reversed() Function: Converts the string into an iterator and joins the reversed characters.
  4. Using Recursion: Calls the function recursively, removing the last character each time.
  5. Using a Stack: TheLast-In-First-Out(LIFO) property of a stack is used to reverse the string.

1. Using String Slicing (Recommended Method)

Slicing in Python provides the easiest way to reverse a string using slicing:


# Reverse a string using slicing
def reverse_string(s):
    return s[::-1]
print(reverse_string("hello"))  # Output: "olleh"

Output:


olleh

How it Works?

  • s[::-1] uses slicing to start from the end (-1 step) and move backward to the beginning.
  • This method is efficient as it directly manipulates string indexing.
  • Why use slicing?

    • It is concise and efficient.
    • It does not require additional loops or functions.

    2. Using a Loop (Iterative Method)

    If you prefer a more traditional approach, you can use a loop to reverse a string

    
    # Reverse a string using a loop
    def reverse_string(s):
        reversed_s = ""
        for char in s:
            reversed_s = char + reversed_s  # Prepend each character
        return reversed_s
    print(reverse_string("Python"))  # Output: "nohtyP"
    

    Output:

    
    nohtyP
    

    How it Works?

    • An empty string reversed_s is initialized.
    • Each character from the original string is prepended to reversed_s.
    • This results in the characters being stored in reverse order.

    Pros and Cons

    Simple to understand and Slightly less efficient than slicing due to string concatenation overhead.

    3. Using the reversed() Function

    Python’s built-in reversed() function can also help reverse a string:
    
    # Reverse a string using reversed() and join()
    def reverse_string(s):
        return "".join(reversed(s))
    print(reverse_string("Python"))  # Output: "nohtyP"
    

    Output:

    
    nohtyP
    

    How it Works?

    • reversed(s) returns an iterator that processes the string in reverse.
    • "".join(reversed(s)) converts the reversed iterator into a string.

    Why use reversed()?

  • It returns an iterator, making it memory-efficient.
  • Works well for both strings and sequences.
  • 4. Using Recursion

    Python Recursion is another way to reverse a string:
    
    # Reverse a string using recursion
    def reverse_string(s):
        if len(s) == 0:
            return s
        return s[-1] + reverse_string(s[:-1])
    print(reverse_string("Python"))  # Output: "nohtyP"
    

    Output:

    
    nohtyP
    

    How it Works?

    • The function keeps calling itself with s[:-1] (excluding the last character) until the base case (len(s) == 0) is met.
    • It then concatenates the last character of each recursive call in reverse order

    Pros and Cons

  • Good for understanding recursion
  • Less efficient for large strings due to stack overflow risk.
  • 5. Using Stack (LIFO Approach)

    A stack follows a Last In, First Out (LIFO) principle, making it a useful way to reverse a string:
    
    # Reverse a string using a stack
    def reverse_string(s):
        stack = list(s)
        reversed_s = ""
        while stack:
            reversed_s += stack.pop()
        return reversed_s
    print(reverse_string("Python"))  # Output: "nohtyP"
    

    Output:

    
    nohtyP
    

    How it Works?

    • The string is converted into a list (stack behavior).
    • pop() function removes characters from the end of the list and appends them to reversed_s.
    • This results in the string being reversed.

    Why use a stack?

  • Useful for understanding data structures.
  • Slower than slicing due to additional operations.
  • Which Method Should You Use?

    MethodPerformanceEase of UseBest Use Case
    Slicing ([::-1])FastestEasiestGeneral use
    LoopModerateSimpleBeginners learning Python
    reversed() FunctionEfficientReadableWorks for both strings & lists
    RecursionSlow for large inputsComplexUnderstanding recursion
    StackSlowExtra memory usageLearning data structures
    Conclusion

    Reversing a string in Python can be achieved in multiple ways, with slicing ([::-1]) being the most efficient and widely used method. However, other approaches like loops, reversed(), recursion, and stacks are also useful for different scenarios. So if you are studying for an exam or preparing for an interview don't forget to practice Reverse a string in Python, also go through our Python For Data Science and AI Training if you want to upgrade in your Python career.

    Practice more with the following articles
    Lambda Function in Python
    Fibonacci Series in Python
    Calculate Armstrong Number in Python
    Factorial Calculator in Python

    FAQs

    Python provides a built-in function called reversed(), which can be used to reverse the characters in a string.

    Is there a reverse function in Python? Yes, the reversed() function allows us to reverse the order of items in a sequence. 

    Slicing is the fastest and most efficient technique for python reverse string. It uses a slice that takes a backward step: -1.
    Share Article
    About Author
    Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

    Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

    Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
    Accept cookies & close this