Best way to loop over a python string backwards

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

    string = "trick or treat"
    for c in reversed(string):
        print c
    

    Will do what I think you want. It uses an iterator. This should work with anything that has __reveresed__() or __len__() and __getitem__() implemented. __getitem__() would have to take int arguments starting at 0.

提交回复
热议问题