3

Let's say I have a string stored in a variable:

a = 'Python'

Now, a[2:4] returns th. How do I reverse this part of the string so that I get ht returned instead?

This is what I tried:

print a[2:4:-1]

But this returned an empty string. Now I know that I can simply store the result of a[2:4] in a new variable and reverse that new variable. But is there a way to reverse part of a string without creating a new variable?

2 Answers 2

3
>>> a = 'Python'
>>> a[2:4]
'th'

Reverse the substring using [::-1]

>>> a[2:4][::-1]
'ht'

or adjust indexes:

>>> a[3:1:-1]
'ht'
Sign up to request clarification or add additional context in comments.

1 Comment

Adjusting indexes seems to be the mist efficient since it doesnt create another temp list.
2

You have to swap the start and end offsets. Did you try a[3:1:-1]? Of course, you have to follow the usual way: initial offset is taken while the end offset isn't (this is why I changed 4 to 3 and 2 to 1).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.