Search code examples
pythonstringslice

How to slice a string in reverse in Python?


I understand how to normally slice a string and reverse it, but don't get how to do both simultaneously.

Let's say

message="hi there"

And I wanna select only the "there" part and reverse it, so the output will be "ereht".

Is there a way to do it? Preferably using only the "message" variable, but any other ways are ok, too.


Solution

  • You would split the string and then reverse it part you desire

    rev = message.split()[-1][::-1]
    

    This solution will also work for the example given in the OP (credit to Kelly Bundy):

    rev = message[:-6:-1]