2
s="Python"

print(s[0:6:-1])

print(s[::-1])

Output

'' # for first print function

'nohtyP' #for second print function

Both have the same meaning but gives different output, I don't understand this why?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 1
    that's a known limitation, you cannot specify start & end values when reversing. The closest you can do is `s[6:0:-1]` but you'll miss a letter. Or `s[0:6][::-1]` – Jean-François Fabre Nov 09 '17 at 09:04
  • 1
    Possible duplicate of [Understanding Python's slice notation](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation). This answer shows that you cannot with the first syntax you tried: https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation/509377#509377 – Jean-François Fabre Nov 09 '17 at 09:07

1 Answers1

1

from this answer to Understanding Python's slice notation:

If stride is negative, the ordering is changed a bit since we're counting down:

>>> seq[::-stride]        # [seq[-1],   seq[-1-stride],   ..., seq[0]    ]
>>> seq[high::-stride]    # [seq[high], seq[high-stride], ..., seq[0]    ]
>>> seq[:low:-stride]     # [seq[-1],   seq[-1-stride],   ..., seq[low+1]]
>>> seq[high:low:-stride] # [seq[high], seq[high-stride], ..., seq[low+1]]

So you notice that when you specify high and/or low bounds when using negative stride, it's not possible to get all elements. You're always short of one.

So s[0:6:-1] prints nothing because low > high. But even with s[6:0:-1] you're short of one letter. The only argument which satisfies your requirements is None (or no argument): s[6:None:-1]

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219