Comparison problem
Peter Hansen
peter at engcorp.com
Sat Nov 26 20:31:53 EST 2005
Tom Anderson wrote:
> On Sat, 26 Nov 2005, Peter Hansen wrote:
>>Tom Anderson wrote:
>>>On Sat, 26 Nov 2005, Chris wrote:
>>>> if item[0:1]=="-":
>>>
>>>item[0:1] seems a rather baroque way of writing item[0]! I'd actually
>>>suggest writing this line like this:
>>
>>Actually, it's not so much baroque as it is safe... item[0] will fail if
>>the string is empty, while item[0:1] will return '' in that case.
>
> Ah i didn't realise that. Whether that's safe rather depends on what the
> subsequent code does with an empty string -
I meant "safe" as in "doesn't throw an exception", as item[0] will when
passed an empty string... sometimes you don't want code to throw an
exception, and you don't want to have to do a separate test for certain
conditions that might do so. This technique is one example.
> an empty string might be some
> sort of error (in this particular case, it would mean that the loop test
> had gone wrong, since bool("") == False), and the slicing behaviour would
> constitute silent passing of an error.
>
> But, more importantly, egad! What's the thinking behind having slicing
> behave like that? Anyone got any ideas? What's the use case, as seems to
> be the fashionable way of putting it these days? :)
Well, since slicing is (I believe, and speaking only roughly) supposed
to return a sequence of the same type as that on which it's operating,
what would be the alternative? Unless you allow slicing to return None,
or raise an exception in certain cases, return a null sequence of the
appropriate type seems to be perfectly logical behaviour when the
requested slice doesn't exist in the input.
But I'm not sure this is from a specific use case so much as a side
effect of other more desirable behaviours of slicing. Asking for this
to behave differently without analyzing the impact it has on slicing in
general is likely to overlook something crucial...
-Peter
More information about the Python-list
mailing list