Manas Chaturvedi
Manas Chaturvedi

Reputation: 5540

Reversing part of a string in Python

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?

Upvotes: 3

Views: 1779

Answers (2)

falsetru
falsetru

Reputation: 368894

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

Reverse the substring using [::-1]

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

or adjust indexes:

>>> a[3:1:-1]
'ht'

Upvotes: 3

Thomas Baruchel
Thomas Baruchel

Reputation: 7507

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

Upvotes: 2

Related Questions