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
3162

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.

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

Discussions

Ways to reverse a string in Python?
Andrew Merrick is having issues with: This is in reference to the Stringcases challenge in the Tuples section of Python collections: More on teamtreehouse.com
🌐 teamtreehouse.com
3
September 11, 2014
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
Challenge: Reverse a string in place
I think the trick to this is using XOR to switch characters in the string without having to use temporary variables to store them. That is, one can switch two variables x and y by using: x = x^y; y = x^y; x = x^y; C++: #include int main(){ char string[]="String to reverse"; std::cout << string << std::endl; int i; int stringsize= sizeof(string) - 1; for(i=0;i More on reddit.com
🌐 r/programmingchallenges
65
22
May 19, 2011
Endianness conversion of hex values in Python 2.x vs 3.x and ELI5 why bytes are used?
The decode method converts the string of hex digits into an actual sequence of bytes. You can't slice the string directly because in the string each character represents only 4 bits, but you want to reverse each 8 bit group (byte). Try printing the reprs of the intermediate values to understand what's going on. In python 3 they removed the ability to decode strings using a method because that operation very rarely makes sense and caused more problem that it solved. You can still use codecs on strings, it's just a little more roundabout now. import codecs x = 'abcd' d = codecs.encode(codecs.decode(x, 'hex')[::-1], 'hex').decode() This kind of stuff is easier if you just realise that you're working with bytes in the first place, rather than trying to keep hold of a string of digits. More on reddit.com
🌐 r/learnpython
5
0
November 6, 2014
🌐
Python.org
discuss.python.org › ideas
Method for reversing strings - Ideas - Discussions on Python.org
February 20, 2025 - 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! There have been several times in my QA career where I am scripting in Python and need to reverse a string, but I have to look up the [::-1] syntax because ...
🌐
Real Python
realpython.com › reverse-string-python
Reverse Strings in Python: reversed(), Slicing, and More – Real Python
July 31, 2023 - The first technique you’ll use to reverse a string involves a for loop and the concatenation operator (+). With two strings as operands, this operator returns a new string that results from joining the original ones. The whole operation is known as concatenation. Note: Using .join() is the recommended approach to concatenate strings in Python.
🌐
Ubiq BI
ubiq.co › home › how to reverse string in python
How to Reverse String in Python - Ubiq BI
May 23, 2025 - The result is reversed string. Here is an example to demonstrate it. data = 'hello world' print(data[::-1]) # dlrow olleh print(data) # hello world · Please note, in the above example, the original string data remains unchanged, since Python strings are immutable.
Find elsewhere
🌐
Great Learning
mygreatlearning.com › blog › it/software development › how to reverse a string in python: the definitive guide
How to Reverse a String in Python: The Definitive Guide
August 25, 2025 - This Tutorial will show you the different ways you can reverse a string in Python. From slicing strings, using the reversed() function and join() method, for or while loops, recursion, and more.
🌐
Hostman
hostman.com › tutorials › how to reverse a string in python
How to Reverse a String in Python | Step-by-Step Guide
December 10, 2024 - We can utilize the reversed() function to reverse a string by using it along with the join() function. The join() function is also a Python built-in function that takes an iterable object as a parameter, it concatenates the elements of this ...
Price   $
Address   1999 Harrison St 1800 9079, 94612, Oakland
🌐
Unstop
unstop.com › home › blog › how to reverse a string in python in 10 ways! (code)
How To Reverse A String In Python In 10 Ways! (Code) // Unstop
December 21, 2023 - There are multiple ways to reverse a string in Python, including the slice operator, extended slicing, reverse() method, loops, recursion, stack, etc.
🌐
dbader.org
dbader.org › blog › python-reverse-string
How to Reverse a String in Python – dbader.org
January 9, 2018 - An overview of the three main ways to reverse a Python string: “slicing”, reverse iteration, and the classic in-place reversal algorithm. Also includes performance benchmarks.
🌐
Better Programming
betterprogramming.pub › benchmarking-the-best-way-to-reverse-a-string-in-python-9c73d87b1b1a
Benchmarking the Best Way to Reverse a String in Python | by Nick Gibbon | Better Programming
September 16, 2019 - The complexity of the appending operation depends on the underlying implementation in the interpreter. Because Python strings are immutable, it is likely that each reversed_output = reversed_output + s[i] takes the current state of the output string and the new character and copies them to a new variable.
🌐
Replit
replit.com › home › discover › how to reverse a string in python
How to reverse a string in Python
February 5, 2026 - It tells Python to move backward through the string one character at a time. By leaving the start and stop indexes empty, you're essentially telling it to include the entire string in this backward traversal. This creates a new, reversed copy of the string without altering the original.
🌐
Medium
medium.com › @khasnobis.sanjit890 › python-reverse-string-74cc521cf8ca
Python Reverse String. Today we are going to write some code… | by Sanjit Khasnobis | Medium
September 10, 2023 - def reverseStr_reversed_method(inputStr): inputStrlist = list(inputStr) outputStrlist = reversed(inputStrlist) outputStr = "".join(outputStrlist) return outputStr ... Here, we have used python inbuilt framework reversed method.
🌐
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.
🌐
Real Python
realpython.com › lessons › python-reverse-string-reversed
Reversing a String Using reversed() (Video) – Real Python
In this lesson, you’ll learn how to reverse a string using the reversed() built-in function. reversed() is a built-in function which returns an iterator that yields sequence items in reverse order.
Published   August 1, 2023
🌐
GUVI
guvi.in › blog › python › python reverse string: 7 effective ways with examples
Python Reverse String: 7 Effective Ways with Examples
January 8, 2026 - When applied to strings, this method enables you to access individual characters or substrings efficiently. To reverse a string using slicing, you utilize the syntax a_string[start:stop:step].
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › reverse-a-string
Reverse a String – Complete Tutorial - GeeksforGeeks
class GfG { static String reverseString(String s) { StringBuilder res = new StringBuilder(); // Traverse on s in backward direction // and add each character to a new string for (int i = s.length() - 1; i >= 0; i--) { res.append(s.charAt(i)); } return res.toString(); } public static void main(String[] args) { String s = "abdcfe"; String res = reverseString(s); System.out.print(res); } } Python ·
Published   2 weeks ago
🌐
4Geeks
4geeks.com › how-to › how-to-reverse-string-in-python
How to reverse string in Python?
July 16, 2025 - One of the easiest ways to reverse a string in Python is by using string slicing.
🌐
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   3 weeks ago
🌐
Team Treehouse
teamtreehouse.com › community › ways-to-reverse-a-string-in-python
Ways to reverse a string in Python? (Example) | Treehouse Community
September 11, 2014 - Strings haven't changed much, but be careful about using Python 2 docs. ... Andrew Merrick Apologies. That's correct. .reverse() only works on lists. I was actually suggesting that you split the string into letters, reverse that list, and join them back together all in one line of code.