简体   繁体   中英

How to reverse a list using slicing?

Let's suppose I have a string text = "Hello". I want to print separately the odd/even positions of the string. I have managed to do this in normal order (see code below).

The problem now is that I want to do the same but starting from the end. That is, odd now equals to "le" and even equals to "olH".

    text = "Hello"

    # Normal order
    odd = text[1::2] # --> "el"
    even = text[0::2] # --> "Hlo"

    # Reverse order (WRONG)
    odd = text[-2::2] 
    even = text[-1::2]

You also need to negate the increment:

oddReverse = text[-2::-2]
evenReverse = text[-1::-2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM