How to Loop over a String in Reverse in Python

Updated onbyAlan Morel
How to Loop over a String in Reverse in Python

Like in most programming languages, strings in Python are essentially an array of individual characters.

This means that we can loop through a string and access each character individually.

A less common but interesting use of this is iterate through a string in reverse order.

In this post, we will look at all the ways you can loop through a string in reverse in Python.

Using the reverse() function

The most straightforward way to do this is to just reverse the string using the reverse() function first, then loop through it.

First, let's define the string we want to use for this:

string = "python"

Then, we can reverse the string using the reverse() function:

string = "python"

reversed_string = reversed(string)

Finally, we can loop through the reversed string:

string = "python"

reversed_string = reversed(string)

for char in reversed_string:
    print(char)
n
o
h
t
y
p

Keep in mind that this will directly modify the string, so if you want to keep the original string intact, you will need to make a copy of it first.

Using the reversed() function

One way to keep the original string intact is to use the reversed() function.

This will simply return a reversed iterator, which we can then loop through, rather than directly modifying the string.

Define the string you want to use, then, we can loop through the reversed string via the iterator:

string = "python"

for char in reversed(string):
    print(char)
n
o
h
t
y
p

Using slicing

Another way to loop through a string in reverse is to use slicing.

Slicing is useful here because you can control the step size, which is the number of characters you want to skip between each iteration.

If you set the step size to -1, it will loop through the string in reverse order.

Here's an example of how to loop through a string in reverse using slicing:

string = "python"

for char in string[::-1]:
    print(char)
n
o
h
t
y
p

This does not modify the original string.

Using range()

The last way to loop through a string in reverse is to use the range() function.

This function is useful because it also has a step size parameter, which you can use to loop through the string in reverse.

Here's an example of how to loop through a string in reverse using the range() function:

string = "python"

for i in range(len(string) - 1, -1, -1):
    print(string[i])
n
o
h
t
y
p

Conclusion

In this post, we looked at all the ways you can loop through a string in reverse in Python.

We looked at the reverse() function, the reversed() function, slicing, and the range() function, all valid ways to loop through a string in reverse.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.