beginner

Reverse a String

Reverse a string in Python.

String reversal is a fundamental operation in programming that helps you understand string manipulation, slicing syntax, and iteration patterns. In this exercise, you will implement a function that reverses a string without using the built-in slicing shortcut.

šŸ“š Concepts & Theory

In Python, strings are immutable sequences of characters, which means you cannot modify them in place. To reverse a string, you have several approaches:

Method 1: String Slicing (Most Pythonic)
Python's slicing syntax allows you to reverse a string with [::-1]. The syntax [start:stop:step] with a step of -1 means "go backwards from end to start".

text = "hello"
reversed_text = text[::-1]  # "olleh"

Method 2: Manual Loop (Educational)
For learning purposes, you can manually build the reversed string by prepending each character:

text = "hello"
result = ""
for char in text:
    result = char + result

Method 3: Using reversed() Function
The built-in reversed() function returns an iterator that you can join:

text = "hello"
reversed_text = "".join(reversed(text))

Each method has its use case: slicing is fastest, manual loop is educational, and reversed() is memory-efficient for large strings.

šŸŽÆ Your Challenge

Write reverse_string without [::-1].

šŸ“ Starter Code

Python
def reverse_string(text):
    pass

print(reverse_string('hello'))
  • Think about building a new string from right to left
  • Each character should be added to the front of your result
  • The prepend operation is: new_char + existing_string

Solution

Python
def reverse_string(text):
    result = ''
    for char in text:
        result = char + result
    return result

print(reverse_string('hello'))

Explanation

This solution uses a manual approach by iterating through each character and prepending it to the result string. By placing each character at the beginning (char + result instead of result + char), we effectively reverse the order. While not the most efficient method due to string immutability creating new objects, it clearly demonstrates the reversal logic. Time complexity: O(n²) due to string concatenation. The slicing method [::-1] would be O(n) and more Pythonic.

āš ļø Common Mistakes to Avoid

  • Forgetting that strings are immutable in Python
  • Using result + char instead of char + result (doesn't reverse)
  • Not returning the result from the function
  • Trying to modify the string in-place like result[i] = char

ā“ Frequently Asked Questions

The slicing method text[::-1] is the fastest and most Pythonic approach.
To help you understand the underlying logic of string reversal through manual iteration.
Yes, but you need to join the result: "".join(reversed(text)). However, the exercise encourages manual implementation for learning.
Because strings are immutable in Python, each concatenation creates a new string object, leading to O(n²) complexity.

šŸ”— Related Exercises