2

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]
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
Randy
  • 79
  • 5

5 Answers5

3

Just do:

ex='The Man'
reverse = ex[::-1]
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
1

Try this :

str='The Man' 
stringlength=len(str)
slicedString=str[stringlength::-1] 
print (slicedString)
Vinay Hegde
  • 1,406
  • 1
  • 9
  • 23
  • It's not a good practice to use a data type as a variable name like `str`. Kindly check the edit suggestion. Moreover, the start index in your case is `len(str)`, which, however, doesn't exist. It should be `len(str) - 1`. – Achint Sharma Jul 14 '19 at 10:39
  • Yes. It would work but you iterating one extra time. Checkout this: https://onlinegdb.com/BkRy-c_br – Achint Sharma Jul 14 '19 at 11:25
1

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]
Achint Sharma
  • 325
  • 3
  • 10
  • How? Is the string saved in circular array – Randy Jul 14 '19 at 10:04
  • You have hard coded the index. What if `ex` value is something like this `stack overflow` ? . Will you do `reverse=ex[13::-1]` ? . Not a good idea though!. – Vinay Hegde Jul 14 '19 at 10:10
  • @VinayHegde This answer was for this specific case. For a generic case, your answer will prove to be a better approach. – Achint Sharma Jul 14 '19 at 10:32
  • @Randy No. The negative index `i` is equivalent to the index `length of string - absolute value of i `, i.e. in your case `-1` is equivalent to `7 - 1` , i.e. `6`. That's how a negative index is defined. Also here, `ex[6::-1]` means: Start from index 6, decrement `1` at a time up to `0`. – Achint Sharma Jul 14 '19 at 10:42
1

This

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

or

ex='The Man'
reverse = ex[-1:-8:-1]
Deadpool
  • 33,221
  • 11
  • 51
  • 91
1
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.

ComplicatedPhenomenon
  • 3,863
  • 2
  • 14
  • 39