[Tutor] Extracting filenames from a List?

Daniel Coughlin kauphlyn@speakeasy.org
Mon, 21 Jan 2002 12:00:36 -0800 (PST)


Hi Troels!

given:

l = ['file.exe','another.gif','evenmore.bat','JPEG.jpg']

---
>>import string
>>for file in l:
>>	if string.lower(file[-3:]) == 'jpg':
>>		l.pop(l.index(file))
'JPEG.jpg'

the file[-3:] is a string slice of the last three characters of the string. the 
string.lower() converts the characters to lower case. pop() removes and 
returns 
the item from the list, if it passes the if test.

you could do whatever you want with the list item once you know it passes the 
test.. if 'extracted' were another list you could write 

extracted.append(l.pop(l.index(file)))

Hope this helps

Daniel

On Mon, 21 Jan 2002, Troels Petersen wrote:

> Hi,
> 
> I have a list containing filenames.
> 
> What I would like to do is to extract all files ending in '.jpg' - the case
> does not matter. Everything ending in '.JpG' should be extracted.
> 
> What is the best way to do this? A Regular expression or..? It should fast
> and something that can be understood by a newbie like me (I need to finish
> the 2 last chapters of 'How to Think Like A Computer Scientist').
> 
> Troels
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>