1
>>> sample = "asdf"
>>> sample[-1:0]

I thought it would start with the last character up to the first position (but not including). However, it returns '' when I expected f. Why is this happening?

Wright
  • 3,370
  • 10
  • 27
jojojo
  • 13
  • 3

2 Answers2

3

To go backwards towards the first element, you need a third argument to your slice, the stride:

sample[-1:0:-1]

This defaults to 1, which moves forward one step at a time; setting it to -1 moves backwards instead.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • what if the last step is 0? I guess it doesn't move? and if it's 2 then it moves to the left two at a time? – jojojo Feb 07 '18 at 01:21
  • 1
    @jojojo when they say "last piece" they mean the "c" in sample[a:b:c] – joshuakcockrell Feb 07 '18 at 01:22
  • Python 1.4 introduced the third ("step" / "stride") element of slice notation. – Charles Duffy Feb 07 '18 at 01:23
  • That doesn't answer the question. The user expected the value "f", your response delivers the value "fds". – schoulten Feb 11 '23 at 18:36
  • @schoulten, the OP accepted it; that's direct evidence as to their expectations. (They didn't say they _wanted_ `f`, they said they _expected_ `f`; it was a "why does X happen?" question, not a "how do I do Y?" question) – Charles Duffy Feb 12 '23 at 16:16
0

Remember the way to go about it is start, stop and step in the square brackets, you got the order wrong!

ChameleonX
  • 87
  • 1
  • 10