Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading