You can also do it with recursion:

def reverse(text):
    if len(text) <= 1:
        return text

    return reverse(text[1:]) + text[0]

And a simple example for the string hello:

   reverse(hello)
 = reverse(ello) + h           # The recursive step
 = reverse(llo) + e + h
 = reverse(lo) + l + e + h
 = reverse(o) + l + l + e + h  # Base case
 = o + l + l + e + h
 = olleh
Answer from Blender on Stack Overflow
🌐
DEV Community
dev.to › jeevanizm › reverse-a-string-in-pythin-without-using-any-built-in-function-1m94
reverse a string in python without using any built in function - DEV Community
December 22, 2023 - If you get an interview question ... def reverse_text(text): reversed_text = "" length = len(text) for i in range(length - 1, -1, -1): reversed_text += text[i] print(f"Reversed text: {reversed_text}") # Example usage: text = "hello ...
Discussions

How do I reverse a string in Python? - Stack Overflow
There is no built in reverse method for Python's str object. How can I reverse a string? More on stackoverflow.com
🌐 stackoverflow.com
python - Without using built-in functions, a function should reverse a string without changing the '$' position - Stack Overflow
I need a Python function which gives reversed string with the following conditions. $ position should not change in the reversed string. Should not use Python built-in functions. Function should be... More on stackoverflow.com
🌐 stackoverflow.com
python - Reversing words of a string without using inbuilt functions - Code Review Stack Exchange
I was wondering if I could reverse a string without using collections and in-built functions of string, Please do add your thoughts on the approach and if possible do share your way of the solution... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
December 16, 2022
How do you reverse a string without using built-in functions?
Reverse a string without using inbuilt function · Create a new string variable to store the reversed string More on ambitionbox.com
🌐 ambitionbox.com
1
People also ask

How to reverse a string in Python without a reverse function?
You can reverse a string in Python using slicing: reversed_string = original_string[::-1].
🌐
guvi.in
guvi.in › blog › python › python reverse string: 7 effective ways with examples
Python Reverse String: 7 Effective Ways with Examples
What is a reversed function in Python?
The reversed() The function in Python returns an iterator that accesses the given sequence in the reverse order. It works with sequences like lists, tuples, and strings.
🌐
guvi.in
guvi.in › blog › python › python reverse string: 7 effective ways with examples
Python Reverse String: 7 Effective Ways with Examples
Can you use reverse () on a string?
No, the reverse() The method cannot be used on a string in Python, as it is specifically designed for lists.
🌐
guvi.in
guvi.in › blog › python › python reverse string: 7 effective ways with examples
Python Reverse String: 7 Effective Ways with Examples
🌐
Medium
medium.com › uniquely-content › write-a-function-to-reverse-a-string-without-using-built-in-reverse-methods-f0d4680997e5
Write a function to reverse a string without using built-in reverse methods. | by Aqila N | Fareeshubs Technologies | Medium
October 19, 2025 - 🔄 Approach 1: Using a Loop We’ll ... Python Code Example: def reverse_string(input_str): reversed_str = "" for i in range(len(input_str) - 1, -1, -1): reversed_str += input_str[i] return reversed_str...
Top answer
1 of 14
3168

Using slicing:

>>> 'hello world'[::-1]
'dlrow olleh'

Slice notation takes the form [start:stop:step]. In this case, we omit the start and stop positions since we want the whole string. We also use step = -1, which means, "repeatedly step from right to left by 1 character".

2 of 14
329

What is the best way of implementing a reverse function for strings?

My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:

>>> 'a string'[::-1]
'gnirts a'

or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:

>>> ''.join(reversed('a string'))
'gnirts a'

or for readability and reusability, put the slice in a function

def reversed_string(a_string):
    return a_string[::-1]

and then:

>>> reversed_string('a_string')
'gnirts_a'

Longer explanation

If you're interested in the academic exposition, please keep reading.

There is no built-in reverse function in Python's str object.

Here is a couple of things about Python's strings you should know:

  1. In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.

  2. Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:

    string[subscript]
    

The subscript creates a slice by including a colon within the braces:

    string[start:stop:step]

To create a slice outside of the braces, you'll need to create a slice object:

    slice_obj = slice(start, stop, step)
    string[slice_obj]

A readable approach:

While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:

def reverse_string_readable_answer(string):
    return ''.join(reversed(string))

Most performant approach:

Much faster is using a reverse slice:

'foo'[::-1]

But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.

start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]

Implement as Function

To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:

def reversed_string(a_string):
    return a_string[::-1]

And usage is simply:

reversed_string('foo')

What your teacher probably wants:

If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:

def reverse_a_string_slowly(a_string):
    new_string = ''
    index = len(a_string)
    while index:
        index -= 1                    # index = index - 1
        new_string += a_string[index] # new_string = new_string + character
    return new_string

This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.

Best Practice

Theoretically better is to collect your substrings in a list, and join them later:

def reverse_a_string_more_slowly(a_string):
    new_strings = []
    index = len(a_string)
    while index:
        index -= 1                       
        new_strings.append(a_string[index])
    return ''.join(new_strings)

However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.

Timings

Here are the timings:

>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265

CPython optimizes string concatenation, whereas other implementations may not:

... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

🌐
YouTube
youtube.com › watch
Write A Python Program To Reverse A String Without Using Built-In Functions - YouTube
Hello Programmers, Welcome to my channel.In this video you will learn about how to Write A Python Program To Reverse A String Without Using Built-In Function...
Published   February 16, 2024
🌐
Stack Overflow
stackoverflow.com › questions › 52288055 › without-using-built-in-functions-a-function-should-reverse-a-string-without-cha
python - Without using built-in functions, a function should reverse a string without changing the '$' position - Stack Overflow
P.S. it's a travesty to write this in Python! ... def merge(template, data): for c in template: yield c if c == "$" else next(data) data = "foo$barbaz$$" "".join(merge(data, reversed([c for c in data if c != "$"]))) 'zab$raboof$$' ... Sign up to request clarification or add additional context in comments. ... Wrote this without using any inbuilt functions. Hope it fulfils your criteria - string = "zytho$n" def reverse(string): string_new = string[::-1] i = 0 position = 0 position_new = 0 for char in string: if char=="$": position = i break else: i = i + 1 j = 0 for char in string_new: if char=="$": position_new = i break else: j = j + 1 final_string = string_new[:position_new]+string_new[position_new+1:position+1]+"$"+string_new[position+1:] return(final_string) string_new = reverse(string) print(string_new)
Find elsewhere
🌐
CodeSpeedy
codespeedy.com › home › reverse string without using function in python
Reverse string in Python without using function- CodeSpeedy
March 16, 2022 - ... Now, since we are iterating, we will be using the iterating variable. We will concatenate the empty string str with the value of an iterating variable which will reverse the string one letter at a time.
Top answer
1 of 3
5

Write functions

You show the reversal of two strings: John Doe and Happy new year! 2022. But your code can only reverse one string. If you wanted to reverse the other string as well, you'd have to duplicate the code.

Instead, write a function. They can be called multiple times.

def reverse_words(sentence):
    ... your code here ...
    return final_str

str1 = "John Doe"
reversed1 = reverse_words(str1)
print(f"string: {str1}\nlen: {len(str1)}")
print(f"Reversed_string: {reversed1}\nlen: {len(reversed1)}")

str2 = "Happy new year! 2022"
reversed2 = reverse_words(str2)
print(f"string: {str2}\nlen: {len(str2)}")
print(f"Reversed_string: {reversed2}\nlen: {len(reversed2)}")

When writing functions, use type-hints and """doc-strings""" to provide additional information about how to use the function:

def reverse_words(sentence: str) -> str:
    """
    Reverse the words of a string.

    >>> reverse_words("John Doe")
    'Doe John'

    >>> reverse_words("Happy new year! 2022")
    '2022 year! new Happy'
    """

    ... your code here ...

    return final_str

With the above function definition, help(reverse_words) will describe the function in much the same way that help(print) describes the print function.

As a bonus, the >>> text in the """doc-string""" can be used for testing, via the doctest module.

Variable Naming

What is space_counter? At first read, I thought you were counting spaces, but it turns out that isn't quite correct:

space_counter = 0
for ...:
    if char == " ":
        space_counter += 1
        if space_counter == 1:
            ...
        elif space_counter == 2:
            ...
            space_counter = 1

The "counter" starts at 0. At the first space, it increments to 1 and one action is performed. At the second and any subsequent space, it increments to 2 and is immediately reset to 1. Since it can only take on the values 0, 1 or 2, it is not really a counter.

It appears you are trying to do something different on the first space verses any subsequent space. A boolean "flag" is more descriptive in these cases:

seen_space = False
for ...:
    if char == " ":
        if not seen_space:
            ...
            seen_space = True
        else:
            ...

temp, a_str, and b_str are all similarly not descriptive variable names. final_str seems more descriptive, but it is used in statements like final_str = temp + " " + final_str, which means its value is not really "final", so again, it is not the best name either.

Iteration

for index in range(len(str1)):
    char = str1[index]
    ...

Using range(len(...) in a for loop is frowned upon in polite Python circles. If index is required in the body of the loop, enumerate(...) is preferred:

for index, char in enumerate(str1):
    ...

Special cases

elif index == len(str1) - 1 is executed on every non-space iteration of the loop. If your string is very, very long, this could be a source of inefficiency. It is testing for the end of the string, which happens at the end of the loop. Why not move this end-of-loop code out of the loop?

for index in range(len(str1)):
    ...
    if char == " ":
        ...
    else:
        temp += char

if temp != "":
    if final_str != "":
        final_str = temp + " " + final_str
    else:
        final_str = temp

Iteration (reprise)

By removing the index == len(str1) - 1 test in the loop body, we find we no longer need the index variable at all, so enumerate(...) is unnecessary, and the for loop can be simplified further:

for char in sentence:
    ...

Special cases (reprise)

Your code handles (and my above modification) has to handle the special case of a single word separately from multiple words. The reason is words end both with a subsequent space AND at the end of the string. We could work around this by intentionally adding a space at the end of the string ourselves, before processing begins.

str1 += " "

This additional sentinel guarantees words will always end with a space, and simplifies the code in the loop. Minor additional processing at the end may be necessary to remove the extra space in the output, depending on the exact implementation.

2 of 3
4

Not wanting to repeat what AJNeufeld has already said, I was curious how long it would take your code to reverse the full text of Moby Dick. While running this experiment, I noticed some funny behavior with spaces. For example, when your code is given " " (3 spaces), it returns " " (two spaces).

You might consider trying some quick tests such as these:

assert reverse_string("Happy new year! 2022") == "2022 year! new Happy"
assert reverse_string(" ") == " "
assert reverse_string("   ") == "   "
assert reverse_string(" a") == "a "
assert reverse_string("a ") == " a"
assert reverse_string(" a ") == " a "
assert reverse_string(" a  bc ") == " bc  a "
assert reverse_string("nospacesinthisone") == "nospacesinthisone"

On my computer, by the way, your approach handles Moby Dick in about 14 seconds! When I initially tried to refactor your code, I achieved a similar result:

Refactor Attempt #1: 13-14 seconds

def reverse_string(string: str) -> str:
    """Reverse the words of a string.

    >>> reverse_words('Happy new year! 2022')
    '2022 year! new Happy'
    """
    new_string, word = "", ""
    for char in string:
        if char == " ":
            new_string = char + word + new_string
            word = ""
        else:
            word += char
    n_missing_chars = len(string) - len(new_string)
    if n_missing_chars != 0:
        new_string = string[-n_missing_chars:] + new_string
    return new_string

Eventually, as you'll see below (if you try it), I managed to reduce the time to 0.1 seconds. It seems driven by replacing new = c + w + new with new += w + c. That this change would make things faster doesn't feel surprising, but I don't truly understand what is happening differently behind the scenes.

Refactor Attempt #2: 0.1 seconds

def reverse_string(string: str) -> str: 
    """Reverse the words of a string.

    >>> reverse_words('Happy new year! 2022')
    '2022 year! new Happy'
    """
    new_string, word = "", ""
    for char in reversed(string):
        if char == " ":
            new_string += word[::-1] + char
            word = ""
        else:
            word += char
    n_missing_chars = len(string) - len(new_string)
    if n_missing_chars != 0:
        new_string += string[:n_missing_chars]
    return new_string

While still adhering to your constraints, I wonder if there is a way to achieve similar or better performance than this without iterating through the string backwards.

Code Snippet: Trying Moby Dick yourself

If you want to reproduce the Moby Dick test yourself, you can use this snippet. You will need to save the full text of Moby Dick as a text file in the same directory as your Python script.

import time


with open("moby_dick.txt", "r") as f:
    string = f.read()

start = time.time()
reversed_moby_dick = reverse_string(string)
end = time.time()
print(f"Execution time: {end - start: .1f} seconds")

As a final comment, were it not for your rules about "built-in functions of string", I likely would have tried using str.join at some point.

This has been a very fun exercise. Thank you for posting it!

🌐
w3tutorials
w3tutorials.net › blog › reverse-a-string-without-using-reversed-or-1
How to Reverse a String in Python Without Using reversed() or [::-1] — w3tutorials.net
def reverse_string_while_loop(s): reversed_str = "" index = len(s) - 1 # Start at the last character while index >= 0: reversed_str += s[index] index -= 1 # Move to the previous character return reversed_str # Test the function original_string = "python" reversed_string = reverse_string_while_loop(original_string) print(f"Original: {original_string}, Reversed: {reversed_string}") # Output: Original: python, Reversed: nohtyp
🌐
GUVI
guvi.in › blog › python › python reverse string: 7 effective ways with examples
Python Reverse String: 7 Effective Ways with Examples
January 8, 2026 - In this example, the reverse_string function takes an input string, applies the reversed() function to create an iterator, and then uses "".join() to form the reversed string. This method is straightforward and leverages Python’s powerful built-in functions to perform the task efficiently.
🌐
GeeksforGeeks
geeksforgeeks.org › python › reverse-string-python-5-different-ways
How to reverse a String in Python - GeeksforGeeks
Reverse the string by iterating over its indices in reverse order using range(). The list comprehension collects characters from last to first, and join() combines them into the final reversed string.
Published   March 3, 2026
🌐
Quora
quora.com › How-do-I-reverse-a-string-in-Python-without-slicing-and-indexing
How to reverse a string in Python without slicing and indexing - Quora
Answer (1 of 4): To reverse a string without using slicing and indexing, there can be two possible approaches: 1. for loop: Using for loop, extract the letters/characters of the string one by one and add them to another empty string in reversed order. Output of the above code 2. reversed metho...
🌐
W3Schools
w3schools.com › python › python_howto_reverse_string.asp
How to reverse a String in Python
Learn how to reverse a String in Python. There is no built-in function to reverse a String in Python.
🌐
AmbitionBox
ambitionbox.com › home › interviews › interview questions
How do you reverse a string without using built-in functions - AmbitionBox
Reverse a string without using inbuilt function · Create a new string variable to store the reversed string · Iterate through the original string from end to start and append each character to the new strin...read more · Reply · Help your peers! Share your answer ·
🌐
Analytics Vidhya
analyticsvidhya.com › home › 5 ways to reverse a string in python
How to Reverse a String in Python in 5 Ways | Reverse Function
February 5, 2025 - Another way to reverse function in Python string is to use the extended slice syntax of the slice operator. We can slice the string with a step of -1, which reverses the string the order of the characters. Here’s an example:
🌐
Linuxize
linuxize.com › home › python › how to reverse a string in python
How to Reverse a String in Python | Linuxize
August 1, 2021 - Python doesn’t have any built-in functions to reverse the string, but we can use other methodsto reverse the string.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › reverse-string-without-using-any-temporary-variable
Reverse string without using any temporary variable - GeeksforGeeks
# Python3 Program to reverse a ... while (start < end): # XOR for swapping the variable str = (str[:start] + chr(ord(str[start]) ^ ord(str[end])) + str[start + 1:]); str = (str[:end] + chr(ord(str[start]) ^ ord(str[end])) ...
Published   July 23, 2025
🌐
Python Guides
pythonguides.com › python-program-to-reverse-a-string
How To Reverse A String In Python?
January 12, 2026 - Using the reversed() function is a clear and flexible way to reverse a string without slicing, especially when you want to understand how iteration works in Python.