Best way to loop over a python string backwards

后端 未结 11 1922
無奈伤痛
無奈伤痛 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:10

    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.

提交回复
热议问题