Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 828
clwen Avatar asked Nov 01 '11 01:11

clwen


1 Answers

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.

like image 160
Raymond Hettinger Avatar answered Oct 03 '22 20:10

Raymond Hettinger