Best way to loop over a python string backwards

后端 未结 11 1949
無奈伤痛
無奈伤痛 2020-12-03 02:16

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          


        
11条回答
  •  孤街浪徒
    2020-12-03 03:09

    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.

提交回复
热议问题