"str.contains(part)" or alternatives?

Joseph A. Knapka jknapka at earthlink.net
Thu Sep 12 06:18:34 CEST 2002


"Delaney, Timothy" wrote:
> 
> > From: Joseph A. Knapka [mailto:jknapka at earthlink.net]
> >
> > So in 2.3, can I do this and get the expected result?
> >
> > >>> "" in "abc"
> > 1
> 
> Yes - this has been hotly debated and defined as true.
> 
> > >>> for subst in "abc":
> > ...   print subst
> > ...
> > <empty string>
> > a
> > ab
> > abc
> > b
> > bc
> > c
> 
> No. Iterating over a string is defined to return each single character in
> turn. Remember:
> 
>     for subst in "abc":
> 
> is equivalent to
> 
>     for subst in iter("abc"):

I didn't know that (never saw "iter()" before).

> and iter("abc") returns "a", "b", "c"
> 
> whilst
> 
>     if subst in "abc":
> 
> is equivalent to
> 
>     if "abc".__contains__(subst):
> 
> (falling back to if subst in iter("abc") if "abc" does not define
> __contains__)
> 
> and str.__contains__ performs a substring match.

Ah. So we have:

not(X in Y <==> X in [Z for Z in Y])

But only if Y is a string. That strikes me as a trifle odd,
but nevertheless I agree that the "substring in string"
behavior seems more useful.

-- Joe
  "I'd rather chew my leg off than maintain Java code, which
   sucks, 'cause I have a lot of Java code to maintain and
   the leg surgery is starting to get expensive." - Me




More information about the Python-list mailing list