Best way to loop over a python string backwards

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

    Python 3 with enumerate and reversed methods:

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

    You can use print(c) just for retrieving each character without the index.

提交回复
热议问题