comparing elements of a list with a string

Evan Klitzke evan at yelp.com
Tue Sep 25 12:01:46 EDT 2007


On Tue, 2007-09-25 at 08:39 -0700, Shriphani wrote:
> Hello all,
> I have a problem here. I have a list named list_of_files which
> contains filenames with their timestamps attached to the name. If I
> have a string "fstab", and I want to list out the files in whose names
> the word fstab appears should I go about like this :
> 
> def listAllbackups(file):
>     list_of_files = os.listdir("/home/shriphani/backupdir")
>     for element in list_of_files:
>          if element.find(file) != -1:
>              date = ###
>              time = ####
>               return (date, time)
> 
> The major trouble is that the return statement causes it to exit after
> attempt one. How do I use the yield statement here?

You can just replace the return statement with a yield statement,
nothing fancy is required. Also, as long as you're using the string.find
method to search for the file, I'd replace it with "if file in element",
which is a bit more idiomatic.

-- 
Evan Klitzke <evan at yelp.com>




More information about the Python-list mailing list