Best way to loop over a python string backwards

后端 未结 11 1920
無奈伤痛
無奈伤痛 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 02:52

     string = "trick or treat"
     for c in string[::-1]:
         print c
    

    I would use that. It is probably quite fast although there may be a slightly better way (but I doubt it).

    EDIT: Actually, with a second test using a program I hacked together, reversed is probably the way to go.

     ==== Results ====
    Sample 1: 0.0225071907043 # Using a for loop
    Sample 2: 0.0100858211517 # Using reversed
    

提交回复
热议问题