searching strings using variables

Larry Bates lbates at swamisoft.com
Tue Jun 15 09:35:30 EDT 2004


Your first attempt is searching for the characters
'16' in a list of integers, which will never be found
and you don't need regular expression overhead to do
this.  You might try.

# list of items to search...
mylist = ['5', '6', '16', '17', '18', '19', '20', '21']
# my variable I want to search with...
myvar = '16'
print mylist.index(myvar)

or

# list of items to search...
mylist = [5, 6, 16, 17, 18, 19, 20, 21]
# my variable I want to search with...
myvar = 16
print mylist.index(myvar)

on the second example you are searching for the characters
'myvar' in the same list of integers, which will never
be found, unless you have something like:

# list of items to search...
mylist = ['5', '6', '16', '17', '18', '19', '20', '21', 'myvar']
print mylist.index('myvar')

HTH,
Larry Bates
Syscon, Inc.

"tgiles" <tgiles at nospamming.kc.rr.com> wrote in message
news:WNxzc.22798$Fd.18743 at twister.rdc-kc.rr.com...
> 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