Best way to loop over a python string backwards

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

    reversed takes an iterable and and returns an iterator that moves backwards. string[::-1] is fine, but it creates a new, reversed string instead. If you just want to iterate, then this will probably better:

    for c in reversed(string):
        print c
    

    If you want to use the reversed string afterwards, creating it once will be better.

提交回复
热议问题