Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

slice - I don't understand slicing with negative bounds in Python. How is this supposed to work?

I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:

>>> s = 'spam'
>>> s[:-1]
'spa'

Why does slicing with no beginning bound and a '-1' return every element except the last one? Is calling s[0:-1] logically the same as calling s[:-1]? They both return the same result. But I'm not sure what python is doing exactly. Any help would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, calling s[0:-1] is exactly the same as calling s[:-1].

Using a negative number as an index in python returns the nth element from the right-hand side of the list (as opposed to the usual left-hand side).

so if you have a list as so:

myList = ['a', 'b', 'c', 'd', 'e']
print myList[-1] # prints 'e'

the print statement will print "e".

Once you understand that (which you may already, it's not entirely clear if that's one of the things you're confused about or not) we can start talking about slicing.

I'm going to assume you understand the basics of a slice along the lines of myList[2:4] (which will return ['c', 'd']) and jump straight into the slicing notation where one side is left blank.

As you suspected in your post, myList[:index] is exactly the same as myList[0:index].

This is also works the other way around, by the way... myList[index:] is the same as myList[index:len(myList)] and will return a list of all the elements from the list starting at index and going till the end (e.g. print myList[2:] will print ['c', 'd', 'e']).

As a third note, you can even do print myList[:] where no index is indicated, which will basically return a copy of the entire list (equivalent to myList[0:len(myList)], returns ['a', 'b', 'c', 'd', 'e']). This might be useful if you think myList is going to change at some point but you want to keep a copy of it in its current state.

If you're not already doing it I find just messing around in a Python interpreter a whole bunch a big help towards understanding these things. I recommend IPython.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...