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".

Answer from Paolo Bergantino on Stack Overflow
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.

Discussions

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
Why does [::1] reverse a string in Python?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
15
12
September 21, 2023
Method for reversing strings - Ideas - Discussions on Python.org
I would like to add a .reverse() method for strings. I think most modern languages have something like that and [::-1] is a bit archaic with little charm. There may be other methods like splitting the string, reversing the resulting list, and then joining it back, but that’s a bit of work! More on discuss.python.org
🌐 discuss.python.org
2
February 20, 2025
7 proven methods to reverse the python string in 2021
"".join(sorted(a, reverse=True)) will not reverse a string. >>> a = "hello world" >>> "".join(sorted(a, reverse=True)) 'wroolllhed ' There's a deeper problem with articles like this, though. Reversing a string is a trivial task (i.e., it's something for a beginner to learn). Giving seven different methods with no explanation on if one is better than another is not good teaching, especially when some don't even work and others are pointlessly verbose. More on reddit.com
🌐 r/Python
8
0
December 4, 2021
🌐
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.
🌐
CodeSpeedy
codespeedy.com › home › reverse string without using function in python
Reverse string in Python without using function- CodeSpeedy
March 16, 2022 - Since we are not using any function, we will need an empty string so that we can concatenate it with each letter of the string using a for loop which we will be discussing in the next step. ... 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!

🌐
24HourAnswers
24houranswers.com › technical-tutoring-tips › How-to-Reverse-a-String-in-Python
How to Reverse a String in Python
October 13, 2021 - In Python, strings are iterable and there is no included function to reverse a string. One rationale for excluding a string.reverse() method is to give Python developers an incentive to leverage the power of this special circumstance.
Find elsewhere
🌐
Javatpoint
javatpoint.com › how-to-reverse-a-string-in-python
How to reverse a string in Python - Javatpoint
How to reverse a string in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, basics, data types, operators, etc.
🌐
Linuxize
linuxize.com › home › python › how to reverse a string in python
How to Reverse a String in Python | Linuxize
August 1, 2021 - In Python, a string is a sequence of Unicode characters. Though Python supports numerous functions for string manipulation, it doesn’t have an inbuilt function or method explicitly designed to reverse the string.
🌐
Educative
educative.io › answers › how-do-you-reverse-a-string-in-python
How do you reverse a string in Python?
In Python, strings are ordered sequences of character data. There is no built-in method to reverse a string.
🌐
Simplilearn
simplilearn.com › home › resources › software development › how to reverse a string in python: a definitive guide
How to Reverse a String in Python: A Definitive Guide
March 27, 2025 - Did you know that there is no built-in function to reverse a String in Python? Discover more about reversing strings, ways to reverse them and more now!
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
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
🌐
Hostman
hostman.com › tutorials › how-to-reverse-a-string-in-python
How to Reverse a String in Python | Step-by-Step Guide
If we want to reverse a string using the basic programming structures without utilizing a built-in function, we can achieve this with traditional Python for loop.
🌐
Career Karma
careerkarma.com › blog › python › python reverse string: a step-by-step guide
Python Reverse String: A Step-By-Step Guide | Career Karma
December 1, 2023 - There is no function explicitly designed to reverse a string. When you’re working in Python, you may have a string that you want to reverse. For instance, say you are creating a game.
🌐
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...
🌐
Reddit
reddit.com › r/learnprogramming › why does [::1] reverse a string in python?
r/learnprogramming on Reddit: Why does [::1] reverse a string in Python?
September 21, 2023 -

For example:

txt = "Hello World"[::-1]

Isn't the splice syntax [start : stop: step]? And default of start and stop are the beginning and end of the string? So that would make the above start at the beginning, stop at the end, but step by -1. That feels like it would start at the beginning, then step backwards to...before the beginning of the string?

Sorry for the silly question, I just can't figure out why this syntax works the way it does.

🌐
Python.org
discuss.python.org › ideas
Method for reversing strings - Ideas - Discussions on Python.org
February 20, 2025 - I would like to add a .reverse() method for strings. I think most modern languages have something like that and [::-1] is a bit archaic with little charm. There may be other methods like splitting the string, reversing the resulting list, and then joining it back, but that’s a bit of work!
🌐
Reddit
reddit.com › r/python › 7 proven methods to reverse the python string in 2021
r/Python on Reddit: 7 proven methods to reverse the python string in 2021
December 4, 2021 -

How to reverse the python string now in 2021?

Hello to all python buddies,

You're stirring your cofee, and going to read r/Python. And you love the blog post.

Today, I'm going to make r/Python more lovable to you.

I'm going to show you the 6 proven methods to reverse the python string. Which are easy and quick to do.

So, start these methods

☺️

  1. Reverse the string using slice method

You can reverse the string using slice method.

The slice indicates the [start:end] position.

A start is a position where sequence start. and end is the position where sequence ends.

The first position is 0th index.

So, here you can use [::-1].

The [::-1] means sequence starting from last of the string.

For example,

a = ["hello"]

print(a[::-1])

It'll reverse the python string.

>>> olleh

2. Reversed the string using reversed() &join() methods

First of all, the reversed() method reverse the sequence.

After reversed() with you can join() every iterables as string.

Basically, the join() method join the iterables as a string seperator.

reversed() & join()

After running, this code you'll get something like

👇

output

3. Reversed the string: join() and sorted() method

As you know, sorted() sort the string or sequences in ascending or descending method.

Here, I'm going to use descending order.

For descending order, pass reverse = True inside sorted().

And previously, I've told that join joins the sequences as a string seperator.

For example,

join() & sorted()

Here, you can see that first I've sorted the string in descending order.

After that, I've join every character as a string.

When you run above code, you'll get:--->

output

So, you've get the reversed string as output.

4. Reversed the string using for loop

You can reverse the string using for loop.

To create the reverse string in for loop, you need function with empty string.

The every new string add to the empty string.

After adding, all the string it becomes the reverse string.

For example,

code

After running code, you'll get--->

output

So, here you've seen how to reverse the python string. I've told you the 6 methods.

And here I've shown you the 4 methods.

But I'm going to show you 3 methods more.

That means 7 method for reverse the python string.

So, I've given you 1 bonus method.

To get these 3 methods, check out the

👇

https://www.heypython.com/python-programming/reverse-the-python-string/