__contains__ inconsistencies between Python 2.2 and 2.3

A

Anand S Bisen

Hello

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)True

(Python 2.2)

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 ?

Thanks

ASB
 
S

Steven Bethard

Anand said:
For example

(Python 2.3)
True

(Python 2.2)


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 ?

IIRC, until Python 2.3, __contains__ only accepted strings of length 1.
Before Python 2.3, I think you needed to do something like:

py> x = 'Hello world'
py> x.find('Hello') != -1
True
py> x.find('wrld') != -1
False

STeVe
 
S

Steve Holden

Anand said:
Hello

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)
True

(Python 2.2)


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 ?

Thanks
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
with

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.

regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top