'<char> in <string>' works, why doesnt '<string> in <string>'?

damien morton morton at dennisinter.com
Sun Mar 10 13:59:51 EST 2002


Tim Roberts <timr at probo.com> wrote in message news:<gf1m8u4ouotllon2v7uha8qnnk3vk5rbka at 4ax.com>...
> It would be a clear and unambiguous expression _if_ the "in" operator was a
> substring search operator, but it is not.  It is a set membership operator.
> It works EXACTLY the same way on all sequence types: the right-hand operand
> is a sequence, and the left-hand operand is something that can be an
> element of that sequence type.  You are suggesting an unorthogonal change
> just because it is easier to type than:
> 
>    'the quick brown fox'.find('fox')
> 
> No.  That is NOT a good reason to change a language in an inconsistent way.

The 'in' operator is now a verb that can be defined to mean pretty
much any function with two arguments. It cant be a set membership
operator because python doesnt have sets. The issue at stake is that
its meaning should be well understood. Strings are like sequences in
that their individual elements (characters ONLY) can be accessed as a
sequence, but there are important differences in the kinds of things
people want to do with strings.

>From the persepective of an english speaker, the the string 'fox' is
IN the string 'the quick brown fox'. Under the covers, the IN operator
is defined as the __contains__ function. Clearly, the string 'the
quick brown fox' CONTAINS the string 'fox'. I think the verb IN means
something slightly different for strings than it does for sequences
and dicts.

Check this out:

('fox' in 'the quick brown fox')
('the quick brown fox'.find('fox') != -1)

Which of these expressions is clearer, more intuitive and convenient?

I appreciate your thoughtfull comments, and I agree with you that
inconsistency should be avoided, but I would assert that this should
not be at the cost of intuitiveness, convenience and clarity.



More information about the Python-list mailing list