Beginner String Problems Python

Reverse a String in Python Without Built-ins

Reverse a string in Python using loops, without slicing or reversed().

  • TimeO(n) steps; each string addition can copy the string, so the loop versions may take up to O(n^2) time for long strings
  • SpaceO(n) for the new string
  • Hints3
  • Read2 min
Quick answer

To reverse a string in Python without built-in functions, start with rev = "" and loop over the string, adding each character to the front: rev = ch + rev. Or loop an index from len(s) - 1 down to 0 with a while loop and add s[i] to the end. With slicing allowed, s[::-1] does the same in one step.

String traversalfor and while loopsString concatenationNegative indexing
1

Problem statement

Given a string s, return it reversed. Do not use s[::-1], reversed() or join() for the main answer. Use a loop.

For example, "hello" becomes "olleh". Python strings cannot be changed in place, so you build a new string.

Input

A string s.

Output

The reversed string.

Examples

Example 1
Inputs = "hello"
Output"olleh"

The last character comes first.

Example 2
Inputs = "CodeBegun"
Output"nugeBedoC"

Case is kept as it is. Only the order changes.

Constraints

  • 0 <= len(s) <= 10^4
  • Any characters, including spaces
2

Think before you code

Reveal the questions to ask yourself first
  • If you read the string from left to right, where should each new character go?
  • If you read it from right to left, what is the first index and the last index?
  • Can you change a Python string in place?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Start with an empty string rev = "".
2 Hint 2
In a for loop, put the new character in front: rev = ch + rev.
3 Hint 3
In a while loop, start at i = len(s) - 1 and stop after i = 0.
4

Approach

Reveal the step-by-step approach

Method 1: for loop, add to the front

Go through the string from the start. Each new character goes before what you have, so the first character ends up last.

Method 2: while loop, read from the end

Start i at the last index, len(s) - 1. Add s[i] to the end of rev, then decrease i. Stop when i goes below 0.

Method 3: slicing (when built-ins are allowed)

s[::-1] uses a step of -1, so it reads the string backwards. It is the shortest and the usual choice in real code.

Method Reads string New char goes
for loop left to right to the front
while loop right to left to the end
slicing handled by Python handled by Python

The same idea is useful for checking a palindrome in Python.

5

Dry run

Walk through the example step by step

For loop on "abc". rev starts as "".

ch | rev = ch + rev
---+---------------
a  | "a"
b  | "ba"
c  | "cba"

While loop on "abc". i starts at 2.

i | s[i] | rev
--+------+------
2 | c    | "c"
1 | b    | "cb"
0 | a    | "cba"
-1| stop
6

Solution

Reveal the full Python solution
solution.py
def reverse_for(s):
    rev = ""
    for ch in s:
        rev = ch + rev
    return rev


def reverse_while(s):
    rev = ""
    i = len(s) - 1
    while i >= 0:
        rev += s[i]
        i -= 1
    return rev


for word in ["hello", "CodeBegun", "a", ""]:
    print(repr(word), "->", repr(reverse_for(word)), repr(reverse_while(word)))

Output:

'hello' -> 'olleh' 'olleh'
'CodeBegun' -> 'nugeBedoC' 'nugeBedoC'
'a' -> 'a' 'a'
'' -> '' ''

repr() prints the quotes so you can see the empty string. Both functions give the same answer, including for a single character and an empty string.

Reverse string Python shortcut: slicing

s = "hello"
print(s[::-1])
print("".join(reversed(s)))
olleh
olleh

Use these in projects. In a test that says "without built-in functions", write one of the loops above.

Python string programs: reverse the words

A related question reverses the order of words, not letters:

sentence = "I love Python"
words = sentence.split(" ")
result = ""
for i in range(len(words) - 1, -1, -1):
    result += words[i]
    if i > 0:
        result += " "
print(result)
Python love I

The Java versions are on reverse a string without built-in methods and reverse the order of words. For more Python practice, see the Python interview questions.

TimeO(n) steps; each string addition can copy the string, so the loop versions may take up to O(n^2) time for long strings
SpaceO(n) for the new string
7

Review before the interview

Common mistakes

  • Starting the while loop at len(s), which raises IndexError. The last index is len(s) - 1.
  • Using while i > 0, which skips the first character.
  • Writing rev = rev + ch in the for loop. That copies the string, it does not reverse it.
  • Trying s[0] = "x". Strings in Python are immutable, so this raises TypeError.

Edge cases to test

  • Empty string returns an empty string.
  • One character returns the same character.
  • Spaces and punctuation are reversed like any other character.
  • Some emoji and accented letters are made of more than one code point and can look broken after reversing.

Interview follow-ups

  • Can you reverse a string using recursion?
  • How would you reverse only the vowels in a string?
  • How would you reverse each word but keep the word order?

Keep practising

Practising Python for interviews?

CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us