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
๐ŸŒ
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 tโ€ฆ
๐ŸŒ
Real Python
realpython.com โ€บ reverse-string-python
Reverse Strings in Python: reversed(), Slicing, and More โ€“ Real Python
July 31, 2023 - Inside ReversibleString, you create .reverse(). This method reverses the wrapped string in .data and reassigns the result back to .data. From the outside, calling .reverse() works like reversing the string in place.
Top answer
1 of 14
3161

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.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ reverse-string-python-5-different-ways
How to reverse a String in Python - GeeksforGeeks
We can reverse the string by taking a step value of -1. ... Python provides a built-in function called reversed() which can be used to reverse the characters in a string.
Published ย  October 21, 2017
๐ŸŒ
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.

๐ŸŒ
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.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ fastest way to reverse a string - and it's not extended string splicing?
r/learnpython on Reddit: Fastest way to reverse a string - and it's not extended string splicing?
August 12, 2020 -

An interview question I got was the following:

Write a function that reversed a string s. Speed is important.

I gave them back a 1 liner, returning

s[::-1]

I was told there's a faster method with some optimisations possible.

Some assumptions:

  • Reasonable real world memory limitations.

  • Input string is a valid string.

  • No information on distribution or makeup of strings

How should I have done it?

๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ reverse-string
Reverse String - LeetCode
The input string is given as an array of characters s. You must do this by modifying the input array in-place [https://en.wikipedia.org/wiki/In-place_algorithm] with O(1) extra memory.
๐ŸŒ
Bhrighu
bhrighu.in โ€บ blog โ€บ reverse-a-string-in-python
How to Reverse a String in Python (5 Easy Methods)
Yes, Python has a built-in reversed() function that returns an iterator over a sequence in reverse order. It works on sequences like strings, lists, and tuples. To reverse a string, you must combine reversed() with join() since strings are immutable and do not support in-place modification.
๐ŸŒ
Python.org
discuss.python.org โ€บ ideas
Method for reversing strings - Page 2 - Ideas - Discussions on Python.org
February 21, 2025 - @Rosuav I am not saying reversing things is trivial and there are no gotchas. What I am saying is that [::-1] solves that problem already: Awesome! No worries. Letโ€™s use it to make the language more readable and user friendly? My concern with this topic is probably more along the lines of precisely 2 strings: [::-1] vs reverse() I know every regular in the python.org discussion board is probably comfortable with the former.
๐ŸŒ
Replit
replit.com โ€บ home โ€บ discover โ€บ how to reverse a string in python
How to reverse a string in Python
The correct approach is to call char_list.reverse() on its own line, which modifies the list in-place. Because the method returns None, you don't assign its result to a variable. After the list is reversed, you can then use ''.join() to build ...
๐ŸŒ
Interviewing.io
interviewing.io โ€บ questions โ€บ reverse-string
How to Reverse a String [Interview Question + Solution]
September 13, 2018 - Strings are typically treated as ... a string in place, you need to convert it into a mutable data structure (like an array) first, perform the reversal, and then convert it back to a string....
๐ŸŒ
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.
๐ŸŒ
LogRocket
blog.logrocket.com โ€บ home โ€บ 5 methods to reverse a python string
5 methods to reverse a Python string - LogRocket Blog
June 4, 2024 - new_string = '' ... count = len(input_string) - 1 ... while count >= 0: ... new_string = new_string + input_string[count] ... count = count - 1 ... return new_string >>> w_reverse('?uoy era woH') 'How are you?' Here, we are creating a function and initializing a new variable, the same as the previous example ยท Now we take the length of the input string and subtract it by 1 because the index in Python starts from 0.
๐ŸŒ
Linuxize
linuxize.com โ€บ home โ€บ python โ€บ how to reverse a string in python
How to Reverse a String in Python | Linuxize
August 1, 2021 - Then the list items are reversed in place with the reverse() method, and finally, the list items are joined into a string using the join() method. ... def rev_str_thru_list_reverse(STR): lst = list(STR) lst.reverse() return(''.join(lst)) ...
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-reverse-string-string-reversal-in-python-explained-with-code-examples
Python Reverse String โ€“ String Reversal in Python Explained with Examples
November 10, 2021 - When you're working with Python strings, there are times when you'll have to reverse them, and work with their reversed copies instead. But since Python strings are immutable, you cannot modify or reverse them in place. In Python, there are ...
๐ŸŒ
dbader.org
dbader.org โ€บ blog โ€บ python-reverse-string
How to Reverse a String in Python โ€“ dbader.org
January 9, 2018 - The built-in reversed() function allows you to create a reverse iterator for a Python string (or any sequence object.) This is a flexible and clean solution that relies on some advanced Python featuresโ€”but it remains readable due to the clear naming of the reversed() function. ... Taking the standard โ€œin-placeโ€ character swap algorithm and port it to Python works, but it offers inferior performance and readability compared to the other options.