__contains__ inconsistencies between Python 2.2 and 2.3
steve at holdenweb.com
Fri Mar 4 21:32:53 CET 2005
Anand S Bisen wrote:
> I have been developing a code that works pretty well on my python 2.3
> and now when i am running it on my server where it is programmed to run
> it's giving me errors. I have been using __contains__ method and it
> fails on python 2.2
> For example
> (Python 2.3)
> >> x="Hello World"
> >> print x.__contains__("Hello")
> (Python 2.2)
> >>> x="Hello world"
> >>> print x.__contains__("Hello")
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: 'in <string>' requires character as left operand
> Is there any woraround for this or what am i doing wrong in 2.2 ?
Any use of double-underscores is an indication that magic is at work. In
this case the __contains__ method is intended to be called by the
interpreter when you write
x in s
The __contains__ method was extended for strings in 2.3 so that
construct could be used as a test to see whether s contained x as a
substring. Before that, as the error message explains, it will only test
to see whether a single character is contained in the string (by analogy
1 in [3, 4, 5, 2]
in case you are interested).
So you'll need to use the .find() string method and say
if x.find("Hello") != -1:
... you found "Hello"
because your ISP appears to be using an older version of Python than you.
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.pycon.org/
Steve Holden http://www.holdenweb.com/
More information about the Python-list