Home > Software engineering >  How to slice a string in reverse in Python?
How to slice a string in reverse in Python?

Time:04-23

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.

CodePudding user response:

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]

CodePudding user response:

For your specific question, you can use this:

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

CodePudding user response:

You just need to select the second slice with [1] and then reverse it using [::-1]

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

  • Related