Randy
Randy

Reputation: 79

Slicing to reverse a string does not work in this case

I am a new bee in python. Trying to reverse the string using slicing. It does not work? why?

ex='The Man'
reverse = ex[6:-1:-1]

Upvotes: 2

Views: 257

Answers (5)

ComplicatedPhenomenon
ComplicatedPhenomenon

Reputation: 4199

ex='The Man'
reverse = ex[-1::-1]

The index can start from 0 to len(ex)-1 or -len(ex) to -1. other index will cause out of range.

Upvotes: 1

Ryuzaki L
Ryuzaki L

Reputation: 40078

This

ex='The Man'
reverse = ex[::-1]

or

ex='The Man'
reverse = ex[-1:-8:-1]

Upvotes: 1

Vinay Hegde
Vinay Hegde

Reputation: 1460

Try this :

str='The Man' 
stringlength=len(str)
slicedString=str[stringlength::-1] 
print (slicedString)

Upvotes: 1

Achint Sharma
Achint Sharma

Reputation: 366

This is because start index and end index are the same, i.e., 6 and -1 are one and the same index. You should try:

ex='The Man'
reverse = ex[6::-1]

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71610

Just do:

ex='The Man'
reverse = ex[::-1]

Upvotes: 3

Related Questions