On 28/09/2007, Kevin Walzer <kw@codebykevin.comwrote:
I'm having a problem with searching a list. Here's my code:
mylist = ['x11', 'x11-wm', 'x11-system']
for line in mylist:
if 'x11' in line:
print line
This results in the following output:
x11
x11-wm
x11-system
That output is correct, you are asking your script to print any list
item containing x11 when what you actually wanted was a list item that
is the string 'x11'
mylist = ['x11', 'x11-wm', 'x11-system']
for item in mylist:
if item == 'x11':
print line
If there is only ever one 'x11' in the list you could also consider
print mylist.index('x11')
and
print mylist[mylist.index('x11')]
Also, before iterating the whole list check that 'x11' exists
if 'x11' in mylist:
do stuff
and list comprehesions
print [x for x in mylist if x == 'x11']
HTH :)
Tim Williams