[Tutor] if item.find(extension)!= -1: -- what's the -1?
Kent Johnson
kent37 at tds.net
Sat Feb 6 18:10:41 CET 2010
On Sat, Feb 6, 2010 at 11:35 AM, David <ldl08 at gmx.net> wrote:
> Hello again,
>
> in Knowlton's 2008 book "Python: Create, Modify, Reuse" the author makes
> frequent use of the term -1 in his code, but doesn't tell to what aim. For
> want of search terms Google is not helpful. Could someone please enlighten
> me by means of a one-liner as a reply?
>
> Example Code:
>
> for item in filelist:
> if item.find(extension)!= -1:
> snaplist.append(item)
Wayne has explained the -1; I will add that a more idiomatic way to
write this is
for item in filelist:
if extension in item:
snaplist.append(item)
or using a list comprehension (assuming snaplist starts out empty):
snaplist = [ item for item in filelist if extension in item ]
Assuming extension is a file extension, I would actually use
endswith() to filter the items:
snaplist = [ item for item in filelist if item.endswith(extension) ]
Kent
More information about the Tutor
mailing list