Best way to loop over a python string backwards

What is the best way to loop over a python string backwards?

The following seems a little awkward for all the need of -1 offset:

string = "trick or treat"
for i in range(len(string)-1, 0-1, -1):
    print string[i]

The following seems more succinct, but is it actually generate a reversed string so that there is a minor performance penalty?

string = "trick or treat"
for c in string[::-1]:
    print c

Try the reversed builtin:

for c in reversed(string):
     print c

The reversed() call will make an iterator rather than copying the entire string.

PEP 322 details the motivation for reversed() and its advantages over other approaches.


Here is a way to reverse a string without utilizing the built in features such as reversed. Negative step values traverse backwards.

def reverse(text):
    rev = ''
    for i in range(len(text), 0, -1):
        rev += text[i-1]
    return rev

reversed takes an iterable and and returns an iterator that moves backwards. string[::-1] is fine, but it creates a new, reversed string instead. If you just want to iterate, then this will probably better:

for c in reversed(string):
    print c

If you want to use the reversed string afterwards, creating it once will be better.


Yes, the second syntax shortcut creates an intermediate string and has an associated performance penalty.

The first version is better written as:

for index, char in enumerate(reversed(s)):
   print "pos %d: %s" % (index, char)

Which is easy to comprehend. Neither reversed nor enumerate` need to make a copy of the string.

Also be careful about using string as a variable name, as it is also the name of a module in the standard library.


 string = "trick or treat"
 for c in string[::-1]:
     print c

I would use that. It is probably quite fast although there may be a slightly better way (but I doubt it).

EDIT: Actually, with a second test using a program I hacked together, reversed is probably the way to go.

 ==== Results ====
Sample 1: 0.0225071907043 # Using a for loop
Sample 2: 0.0100858211517 # Using reversed