slicing is "fail-soft" (was Re: Determining if a filename is greater than X characters)

Alex Martelli aleax at
Sun Aug 3 16:55:12 CEST 2003

Irmen de Jong wrote:

> Cy Edmunds wrote:
>> filename = "abcdefgh"
>> if len(filename) > 6:
>>     filename = filename[:6]
>> print filename
>> abcdef
> The if is not necessary, just use
> filename=filename[:6]

Right.  To reiterate the point, which IS very important: differently from
indexing, slicing is FAIL-SOFT -- if you ask for nonexistent parts of a
sequence as part of a slice, you'll just get a shorter resulting sequence
from your slicing.  This often makes for smoother code because less guards
are necessary.

For example, say that I want to check if "the string is non-empty and its
first character is alphabetical".  Coding this as:

    if thestring and thestring[0].isalpha():

is one obvious way -- but a smooth alternative is:

    if thestring[0:1].isalpha():

If the string IS empty, so will thestring[0:1] be (and such a slicing out of
the sequence's boundaries raises NO exception, which is the key point), and
''.isalpha() is False (easy to remember: ''.isXYZ() is False for all
supported XYZ:-), so these conditions are equivalent.


More information about the Python-list mailing list