[Tutor] Help return a pattern from list

Sander Sweers sander.sweers at gmail.com
Mon Jul 5 20:19:21 CEST 2010


On 5 July 2010 19:54, Vineeth Rakesh <vineethrakesh at gmail.com> wrote:
> Can some one help me to return a special pattern from a list.
>
> say list =
> ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
>
> now say I just need to return the files with .mp3 extension. How to go about
> doing this?

Use os.path.splitext() to check for the extension and check if it
equals the extension you want. For example like below idle session:

>>> import os
>>> say_list = ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
>>> mp3_list = [x for x in say_list if os.path.splitext(x)[1].lower() == ".mp3"]
>>> mp3_list
['something1.mp3', 'something2.mp3']

Greets
Sander


More information about the Tutor mailing list