"in" operator for strings

Martijn Faassen m.faassen at vet.uu.nl
Wed Feb 7 09:40:35 EST 2001


Pete Shinners <shredwheat at mediaone.net> wrote:
> with the back and forth going on about the "in" operator and
> dictionaries, i was thinking it would be nice for the "in"
> operator to also check for the presence of substrings in a
> string. for example...


>>>> "Waldo" in "Ralph Emerson"
> 0
>>>> "Waldo" in "Ralph Waldo Emerson"
> 1

'in' already has a meaning for strings, which are sequences of characters:

>>> 'f' in 'foo'
1
>>> 'b' in 'foo'
0

> i find this much more intuitive and graceful than the current
> syntax i am repeatedly using...

>>>> "Ralph Emerson".find("Waldo") != -1
> 0

Why I agree that this looks a bit odd, it isn't that terrible. I'll just dump 
my stance on 'in' here:

Let's not overload 'in' more than it is now. 'in' is already overloaded;
there's the for .. in.. meaning and the x in sequence meaning. 

Now at least these both have to do with sequences. They're not about dicts
and they don't have anything to do with string matching. I think it's not
a good idea to overload this meaning any further. It's okay if a custom
class has an explicit override __in__, though I'd expect this class then
to implement some form of the sequence interface overall.

I don't think all operators have to do something sensible for everything;
in the case of 'in' we obviously cannot even agree on what 'sensible' is.

'in' currently does 'something mumble mumble' with items in sequences. 
Not a very clear definition perhaps, but let's not muddy the waters
further either.

Regards,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list