[Tutor] String slicing off the end question

Alan Gauld alan.gauld at yahoo.co.uk
Tue Dec 22 12:28:47 EST 2020


On 22/12/2020 16:46, David Rock wrote:

>>>> somestring[:10]
> 'python'
> 
> In particular, I was surprised by defining a slice outside the range not
> throwing an exception (eg, in the example above, the string is length 6,
> but setting a stop of 10 doesn't have any issues and appears to just
> return the whole string).  Is this how it's supposed to work? If it is,
> then why?  Is this behavior reliable?

Yes, it's how its defined in the language reference. I couldn't find
the actual reference but the tutorial (Sect 3.1.2) does include
this comment when discussing slicing:

######################
Attempting to use an index that is too large will result in an error:
>>>

>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

However, out of range slice indexes are handled gracefully when used for
slicing:
>>>

>>> word[4:42]
'on'
>>> word[42:]
''

#######################

So an out of bounds *index* is an error but an out of bounds slice
marker degrades "gracefully".

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list