Antman
Antman

Reputation: 493

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]

Upvotes: 1

Views: 88

Answers (1)

user9723177
user9723177

Reputation:

You also need to negate the increment:

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

Upvotes: 5

Related Questions