🌐
DigitalOcean
digitalocean.com › community › tutorials › python-reverse-string
Python Reverse String - 5 Ways and the Best One | DigitalOcean
August 3, 2022 - $ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_slicing("ABç∂EF"*10)' 100000 loops, best of 5: 0.449 usec per loop $ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_list("ABç∂EF"*10)' 100000 loops, best of 5: 2.46 usec per loop $ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_join_reversed_iter("ABç∂EF"*10)' 100000 loops, best of 5: 2.49 usec per loop $ python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.
🌐
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.
Discussions

What is the most efficient way to reverse a string in Python? - Stack Overflow
I'm looking for the most efficient method to reverse a string in Python. While there are several approaches to accomplish this task, I want to know which technique provides the best performance in ... More on stackoverflow.com
🌐 stackoverflow.com
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
Fastest way to reverse a string - and it's not extended string splicing?
I was told there's a faster method with some optimisations possible. If reversing strings is a bottleneck needing optimization, then your codebase might have bigger issues. More on reddit.com
🌐 r/learnpython
70
245
August 12, 2020
Algorithm complexity with strings and slices

The python page on time-complexity shows that slicing lists has a time-complexity of O(k), where "k" is the length of the slice. That's for lists, not strings, but the complexity can't be O(1) for strings since the slicing must handle more characters as the size is increased. At a guess, the complexity of slicing strings would also be O(k). We can write a little bit of code to test that guess:

import time

StartSize = 2097152

size = StartSize
for _ in range(10):
    # create string of size "size"
    s = '*' * size

    # now time reverse slice
    start = time.time()
    r = s[::-1]
    delta = time.time() - start

    print(f'Size {size:9d}, time={delta:.3f}')

    # double size of the string
    size *= 2

This uses a simple method of timing. Other tools exist, but this is simple. When run I get:

$ python3 test.py
Size   2097152, time=0.006
Size   4194304, time=0.013
Size   8388608, time=0.024
Size  16777216, time=0.050
Size  33554432, time=0.098
Size  67108864, time=0.190
Size 134217728, time=0.401
Size 268435456, time=0.808
Size 536870912, time=1.610
Size 1073741824, time=3.192

which shows the time doubles when doubling the size of the string for each reverse slice. So O(n) (k == n for whole-string slicing).

Edit: spelling.

More on reddit.com
🌐 r/learnpython
4
3
December 1, 2019
🌐
Medium
medium.com › better-programming › 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 - Slicing is the most efficient way to reverse a string in python. Reverse to swap inline and reversed for a copy perform well and are clearer. String concatenation, as implemented in the slower algorithms, should be avoided.
🌐
Real Python
realpython.com › reverse-string-python
Reverse Strings in Python: reversed(), Slicing, and More – Real Python
July 31, 2023 - Python provides two straightforward ways to reverse strings. Since strings are sequences, they’re indexable, sliceable, and iterable. These features allow you to use slicing to directly generate a copy of a given string in reverse order.
🌐
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 - Learn how to reverse a string in Python using loops, slicing, recursion, stack, and more. Explore challenges and multiple methods.
🌐
Real Python
realpython.com › lessons › python-reverse-string-custom-algorithm
Reversing a String Using a Custom Algorithm (Video) – Real Python
For example, let’s say you want to reverse the string "HELLO". During the first iteration, the "H" and "O" would be swapped, as the left pointer is equal to 0, and the right pointer is equal to 4. During the second iteration, the left pointer has now been incremented to 1, with the right having been decremented to 3. Therefore, the "E" and the "L" would be swapped. During the third and final iteration, the left and right pointers would both equal 2, and therefore the algorithm would exit, returning the string, "OLLEH".
Published   August 1, 2023
🌐
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)
December 21, 2023 - Here's a Python code for the same: ... bnVtYmVyID0gMTIzNDUNCnJldmVyc2VkX251bWJlciA9IGludChzdHIobnVtYmVyKVs6Oi0xXSkNCg0KcHJpbnQocmV2ZXJzZWRfbnVtYmVyKQ== ... In Python, the fastest algorithm to reverse a string is using slicing with [::-1]. This ...
🌐
GeeksforGeeks
geeksforgeeks.org › 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
Find elsewhere
🌐
Educative
educative.io › home › courses › data structures and algorithms in python › reverse string
Reverse a String Using Stack in Python for LIFO Operations
Explore how to reverse a string using a stack in Python by pushing each character onto the stack and popping them off to get the reversed result. Understand the algorithm and implement it to strengthen your knowledge of stack operations and string manipulation.
🌐
Educative
educative.io › answers › how-do-you-reverse-a-string-in-python
How do you reverse a string in Python?
This technique reverses a string using reverse iteration with the reversed() built-in function to cycle through the elements in the string in reverse order and then use .join() method to merge all of the characters resulting from the reversed ...
🌐
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.
🌐
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.
🌐
Stack Abuse
stackabuse.com › how-to-reverse-string-in-python
How to Reverse String in Python
May 24, 2022 - In this short guide, learn how to reverse a string in Python, with practical code examples and best practices - using the slice notation with a negative step, a for loop, a while loop, join() and reversed().
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.

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

🌐
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.
🌐
Interviewing.io
interviewing.io › questions › reverse-string
How to Reverse a String [Interview Question + Solution]
September 13, 2018 - Space Complexity: O(n). We are using a character array to store the characters of the string. So the space complexity is O(n). If the input to the function is a character array itself or the language supports string mutability, then the space complexity would be O(1), because the algorithm does an in-place reversal of the character array / string.