Eric Suh
Eric Suh

Reputation: 138

Slicing lists and strings to negative zero

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?

Upvotes: 2

Views: 876

Answers (4)

fede_lcc
fede_lcc

Reputation: 23

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'

Upvotes: 2

Håvard
Håvard

Reputation: 10080

'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

Upvotes: 8

Felix
Felix

Reputation: 89606

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".

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208555

-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

Upvotes: 3

Related Questions