if 'hallo' in ['hallooo','halloooooooo'] problem

R

Robert

Hi,

I have a little problem and mybe one of you has got the solution.
I would like to check if a string is in a list of strings.
The following returns true:
if 'hallo' in ['halloooo','hallooooooooo']:
pass

but I want to check if the string is exactly equal to any string in the
list.
How can I do this without the need to do something like this:
def stringInList(self,string,list):
for oneStr in list:
if string == oneStr:
return 1
return 0


Thank you in advance,

Robert
 
P

Peter Hansen

Robert said:
I have a little problem and mybe one of you has got the solution.
I would like to check if a string is in a list of strings.
The following returns true:
if 'hallo' in ['halloooo','hallooooooooo']:
pass
c:\>python
>>> 'hallo' in ['hallooo', 'halllloooo']
False


Given that "if" is not an expression, and so "returns" nothing
at all, please explain what you mean above... clearly the
"in" expression is behaving as you requested...

-Peter
 
J

Jeff Epler

Does it really work the way you describe?

2.2:
'xy' in ['xyz'] 0
'xy' in ['xy', 'xyz']
1

2.3:
'xy' in ['xyz'] False
'xy' in ['xy', 'xyz']
True

2.4 CVS:
'xy' in ['xyz'] False
'xy' in ['xy', 'xyz']
True

The meaning that has changed is "s1 in s2" when s1 is a string not of
length 1, and s2 is a string.

2.2:TypeError: 'in <string>' requires character as left operand

2.3:True

2.4 CVS:True

Jeff
 
V

Vrai Stacey

Robert said:
I have a little problem and mybe one of you has got the solution.
I would like to check if a string is in a list of strings.
The following returns true:
if 'hallo' in ['halloooo','hallooooooooo']:
pass

What version of Python are you using? With 2.2.3 I get the behavior you
want using your first example.

So ...
> if 'hallo' in ['halloooo','hallooooooooo']: print "Hallo!";
> if 'hallo' in ['halloooo','hallo' ]: print "Hallo!";
Hallo!

vrai.
 
R

Robert

Sorry!!!!

the example I gave I did not check. Of course it works.

The problem is somewhere else. My programm was doing this:

if 'hallo' in 'hallooooo':
.....

instead of (what I was thinking):

if 'hallo' in ['hallo']:
.....


so , everything is fine. I did not see, that the variable holding the second
string is a string instead of a list.


Thanks for your replies!!!!!!
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top