How to reverse a String in Python (original) (raw)

Last Updated : 21 Nov, 2024

**Reversing a string is a common task in Python, which can be done by several methods. In this article, we discuss different approaches to reversing a string. One of the simplest and most efficient ways is by using **slicing. Let’s see how it works:

Using string slicing

This **slicing method is one of the simplest and an efficient method to reverse a string. It is easy to remember and best suited for reverse the string quickly.

Python `

s = "GeeksforGeeks" rev = s[::-1] print(rev)

`

**Explanation:

Let's explore the other different methods to reverse the string:

Table of Content

Using reversed() and join()

Python provides a built-in function called **reversed(), which can be used to reverse the characters in a string. This approach is very useful if we prefer to use built-in methods.

Python `

s = "GeeksforGeeks" rev = ''.join(reversed(s)) print(rev)

`

**Explanation:

Using a Loop

If we need more control over the reversal process then we can use a for loop to reverse the string. This method provides a clear view of how the reversal happens character by character.

Python `

s = "GeeksforGeeks"

Initialize an empty string to hold reversed result

rev = ""

Loop through each character in original string

for ch in s:

# Add current character to front of reversed string
rev = ch + rev

print(rev)

`

**Explanation:

Using list comprehension and join()

A more creative approach involves using list comprehension to reverse the string by iterating through its indices. This approach is useful when we need more control during iteration like above approach (**for loop).

Python `

s = "GeeksforGeeks" rev = ''.join([s[i] for i in range(len(s) - 1, -1, -1)]) print(rev)

`

**Explanation:

Using stack

We can use a stack data structure to reverse a string due to its **Last In First Out (LIFO) property. This means that the last element added to the stack will be the first one to be removed, this effectively reversing the order of the elements.

**Note: **list can be easily used to simulate the behavior of a **stack. It provides built-in methods like ****.append()** and****.pop()**, which make it suitable for stack operations.

Python `

s = "GeeksforGeeks"

Convert the string into a list to use it as a stack

stack = list(s)

Initialize an empty string to hold the reversed result

rev = ""

Continue looping until the stack is empty

while stack:

# Remove the top element from the stack 
# and add it to the reversed string
rev += stack.pop()

print(rev)

`

**Explanation:

**Note: Python also has a **collections.deque module, which provides a **deque (double-ended queue) that can also be used as a **stack.

Which method to choose?