searching strings using variables

Sylvain Hellegouarch sh at defuze.org
Tue Jun 15 06:17:04 EDT 2004


Hi tom,

why not trying a :

if int(myvar) in mylist:
    print "OK"
else:
    print "Not in"

- Sylvain

tgiles wrote:

> Hi, all. Another bewildered newbie struggling with Python goodness. This 
> time it's searching strings. The goal is to search a string for a value. 
> The string is a variable I assigned the name 'myvar'. however, it 
> doesn't seem to be seeing it... Here's a snippet.
> 
> import re
> 
> # list of items to search...
> mylist = [ 5 , 6 , 16 , 17 , 18 , 19 , 20 , 21 ]
> # my variable I want to search with...
> myvar = '16'
> print re.search('myvar','mylist')
> 
> ... just returns none. Tried it also with...
> 
> mylist.index('myvar')
> 
> to see if I could spook it out but I get a ValueError (not in list) so 
> it looks like it won't see it either. I did vague permutations trying to 
> make it work but no go. I'm thinking it may be one of those "forest for 
> the trees" things, i've been looking at it too hard. Any ideas?
> 
> many thanks in advance!
> 
> tom





More information about the Python-list mailing list