2

I've read the Python informal tutorial on slicing, which all makes sense to me except for one edge case. It seems like

'help'[:-0]

should evaluate to 'help', but it really evaluates to ''. What's a good way to think about negative index slicing so that this particular edge case makes sense?

Eric Suh
  • 138
  • 3

4 Answers4

8

'help'[:-0] is actually equal to 'help'[:0], in which case it makes sense that it evaluates to ''. In fact, as you can see from the interactive python interpreter, -0 is the same as 0:

>>> -0
0
Håvard
  • 9,452
  • 1
  • 39
  • 46
  • 1
    That's not an "assume". You assumed very little. You actually ran actual code and actually proved what the actual result is. Drop the "assume" business from this otherwise good answer. – S.Lott Apr 01 '11 at 23:51
3

-0 == 0, so 'help'[:-0] is equivalent to 'help'[0:0], which I think you will agree should be ''.

The following question has some good general info on slices and how to think of them: Explain Python's slice notation

Community
  • 1
  • 1
Andrew Clark
  • 192,132
  • 30
  • 260
  • 294
1

As the others have said, -0 == 0, in which case the '' result is correct. I think you're looking for:

'help'[:]

When slicing, if you omit the start it starts from 0, if you omit the end, it advances until the end of the collection (in your case a string). Thus, [:] means "beginning to end".

Felix
  • 86,568
  • 42
  • 148
  • 166
1

As others have said, -0 == 0 therefore the output '' makes complete sense.

In case you want a consistent behaviour when using negative indices, you could use len() in the slicing index:

>>> a = 'help'
>>> a[:len(a)-0]
'help'
fede_lcc
  • 11
  • 5