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
🌐
W3Schools
w3schools.com › python › ref_list_reverse.asp
Python List reverse() Method
The reverse() method reverses the sorting order of the elements. ... The built-in function reversed() returns a reversed iterator object. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an ...
🌐
W3Schools
w3schools.com › python › ref_func_reversed.asp
Python reversed() Function
The reversed() function returns a reversed iterator object. ... The iter() function returns an iterator object. The list.reverse() method reverses a List. ... If you want to use W3Schools services as an educational institution, team or enterprise, ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › reverse-string-python-5-different-ways
How to reverse a String in Python - GeeksforGeeks
Let's explore the other different methods to reverse the string: ... Python provides a built-in function called reversed(), which can be used to reverse the characters in a string.
Published   November 21, 2024
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.

🌐
W3Schools
w3schools.com › python › python_strings.asp
Python Strings
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary · Built-in Modules Random Module Requests Module Statistics Module Math Module cMath Module · Remove List Duplicates Reverse a String Add Two Numbers
Find elsewhere
🌐
W3Schools
w3schools.com › python › python_ref_string.asp
Python String Methods
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary · Built-in Modules Random Module Requests Module Statistics Module Math Module cMath Module · Remove List Duplicates Reverse a String Add Two Numbers
🌐
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.
🌐
Real Python
realpython.com › reverse-string-python
Reverse Strings in Python: reversed(), Slicing, and More – Real Python
July 31, 2023 - In this step-by-step tutorial, you'll learn how to reverse strings in Python by using available tools such as reversed() and slicing operations. You'll also learn about a few useful ways to build reversed strings by hand.
🌐
W3Schools
w3schools.com › python › python_strings_exercises.asp
Python - String Exercises
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... Now you have learned a lot about Strings, and how to use them in Python. ... If you want to use W3Schools ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-reverse-string
Python Reverse String - 5 Ways and the Best One | DigitalOcean
August 3, 2022 - I understand the first one is to tell Python to look at all the elements in string, the second one I’m unsure about but [ -1] means that the first item to return needs to be at length [-1]. What does the second colon operator tell Python to do? Thanks ... Hi, Thank you for the explanation. I also wanted to know how to add new lines to the output. For example I have made a reverse string input program: def reverse_slice(s): return s[::-1] s=input('enter a string ') print(s[::-1]) How would I a make my answer be on multiple lines?
🌐
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…
🌐
W3Schools
w3schoolsua.github.io › python › python_strings_methods_en.html
Python - String Methods. Lessons for beginners. W3Schools in English
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary · Random Module Requests Module Statistics Module Math Module cMath Module · Remove List Duplicates Reverse a String Add Two Numbers
🌐
W3Schools
w3schools.com › python › python_strings_modify.asp
Python - Modify Strings
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary · Built-in Modules Random Module Requests Module Statistics Module Math Module cMath Module · Remove List Duplicates Reverse a String Add Two Numbers
🌐
W3Schools
w3schools.com › python › ref_string_swapcase.asp
Python String swapcase() Method
The swapcase() method returns a string where all the upper case letters are lower case and vice versa. ... No parameters. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › reverse-words-given-string-python
Reverse Words in a Given String in Python - GeeksforGeeks
October 27, 2025 - A deque (double-ended queue) is efficient for large strings, as it allows O(1) pops from both ends. This method uses pop() to retrieve words in reverse order. ... from collections import deque s = "Python is fun" words = deque(s.split()) res = "" while words: res += words.pop() + " " res = res.strip() print(res)
🌐
W3Schools
w3schools.com › python › python_string_formatting.asp
Python String Formatting
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary · Built-in Modules Random Module Requests Module Statistics Module Math Module cMath Module · Remove List Duplicates Reverse a String Add Two Numbers
🌐
Flexiple
flexiple.com › python › python-reverse-string
Reverse String In Python - Flexiple
In Python, a stack can be easily simulated using a list. Here's how the process works. Initialize an empty list to act as the stack. Iterate through each character in the input string. Push each character onto the stack (append it to the list).