DocsHub
PythonBeginner

Reverse a String

Learn how to reverse a string in Python using different approaches.

Reverse a String

Problem

Given a string, reverse it.

Input:  "hello"
Output: "olleh"

Input:  "Python"
Output: "nohtyP"

Input:  "racecar"
Output: "racecar"

Input:  "Hello World"
Output: "dlroW olleH"

Logic

  1. Take the string
  2. Read it from the last character to the first
  3. Build the reversed string
  4. Return it

Flow

Yes No Start Take the string Start from the last character More characters? Add character to result Move to previous character Return reversed string

Solution 1 — using string slicing

The most Pythonic and shortest way. [::-1] reads the string backwards.

def reverse_string(s):
    # [::-1] means start from end, go to start, step -1
    return s[::-1]


print(reverse_string("hello"))        # olleh
print(reverse_string("Python"))       # nohtyP
print(reverse_string("racecar"))      # racecar
print(reverse_string("Hello World"))  # dlroW olleH

Code Execution — Solution 1

Trace through reverse_string("hello"):

StepCodeResult
Inputs = "hello""hello"
Slice"hello"[::-1]reads o, l, l, e, h
Return"olleh"

[::-1] means:

  • start — end of string
  • stop — beginning of string
  • step — -1 means move one step backwards

Solution 2 — using a loop

Loop through the string from the last character to the first and build the result one character at a time.

def reverse_string(s):
    reversed_str = ""

    # range(len(s)-1, -1, -1) starts from last index down to 0
    for i in range(len(s) - 1, -1, -1):
        reversed_str += s[i]   # add character at index i to result

    return reversed_str


print(reverse_string("hello"))        # olleh
print(reverse_string("Python"))       # nohtyP
print(reverse_string("racecar"))      # racecar
print(reverse_string("Hello World"))  # dlroW olleH

Code Execution — Solution 2

Trace through reverse_string("hello"):

"hello" has 5 characters — indexes 0, 1, 2, 3, 4

range(4, -1, -1) gives us 4, 3, 2, 1, 0

Loopis[i]reversed_str
Start""
1st4"o""o"
2nd3"l""ol"
3rd2"l""oll"
4th1"e""olle"
5th0"h""olleh"
Done"olleh"

Solution 3 — using a loop and prepending

Loop forward through the string but add each character to the front of the result instead of the back.

def reverse_string(s):
    reversed_str = ""

    for char in s:
        # add each character to the FRONT — not the back
        reversed_str = char + reversed_str

    return reversed_str


print(reverse_string("hello"))        # olleh
print(reverse_string("Python"))       # nohtyP
print(reverse_string("racecar"))      # racecar
print(reverse_string("Hello World"))  # dlroW olleH

Code Execution — Solution 3

Trace through reverse_string("Python"):

Loopcharchar + reversed_strreversed_str
Start""
1st"P""P" + "" "P"
2nd"y""y" + "P""yP"
3rd"t""t" + "yP""tyP"
4th"h""h" + "tyP""htyP"
5th"o""o" + "htyP""ohtyP"
6th"n""n" + "ohtyP""nohtyP"
Done"nohtyP"

Each new character goes to the front — so the first character of the original string ends up last in the result.


Solution 4 — using a stack

A stack is Last In First Out — push all characters in, pop them all out. Popping reverses the order.

def reverse_string(s):
    stack = []

    # push every character onto the stack
    for char in s:
        stack.append(char)   # append = push

    reversed_str = ""

    # pop every character off the stack
    while stack:
        reversed_str += stack.pop()   # pop() removes and returns the last item

    return reversed_str


print(reverse_string("hello"))        # olleh
print(reverse_string("Python"))       # nohtyP
print(reverse_string("racecar"))      # racecar
print(reverse_string("Hello World"))  # dlroW olleH

Code Execution — Solution 4

Trace through reverse_string("hello"):

Push phase:

Stepcharstack
1st"h"["h"]
2nd"e"["h", "e"]
3rd"l"["h", "e", "l"]
4th"l"["h", "e", "l", "l"]
5th"o"["h", "e", "l", "l", "o"]

Pop phase:

Stepstack.pop()reversed_strstack
1st"o""o"["h", "e", "l", "l"]
2nd"l""ol"["h", "e", "l"]
3rd"l""oll"["h", "e"]
4th"e""olle"["h"]
5th"h""olleh"[]
Done"olleh"

The stack solution introduces an important concept — LIFO (Last In, First Out). The last character pushed is the first one popped. This naturally reverses the order. Stacks are a fundamental data structure used in many algorithms.


Which solution to use?

SolutionHowBest when
Solution 1[::-1] slicingClean production code
Solution 2Loop backwards by indexYou want to practice index-based loops
Solution 3Loop forward, prependYou want to understand string building
Solution 4Stack push and popYou want to understand stack data structure

Output

olleh
nohtyP
racecar
dlroW olleH

On this page