Best way to loop over a python string backwards Best way to loop over a python string backwards python python

Best way to loop over a python string backwards


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.