[Tutor] Removing itens from a list
Tom Jenkins
tjenkins@devis.com
15 Jan 2002 12:55:29 -0500
Hello and welcome,
On Tue, 2002-01-15 at 12:36, Marco A. Sousa wrote:
> Hi. This is my first message to this great list. Wish I find out about
> you before :) Sorry for my english, we speak portuguese here.
>
>
> My question is:
>
> In the following list,how do I remove every item with "orange" on it?
> l = ['I like Orange juice','orange','OranGes are good','I like apple']
>
>
> I think I should use re module, but dont now how to use it.
> Do you know any site that explain the use of re module or regex with python ?
you could use a regular expression however i would use a list
comprehension (assuming python 2.x)
results = [x for x in l if x.lower().find('orange') == -1]
what is going on here is
- we loop over 'l' putting the item in 'x'
- call lower() on x which lowercases the string
- call find('orange') on the lowercased string. if the return value of
that call is -1 then 'orange' does not appear in the string
- check our return value from find() against -1, if they are equal then
append the value of 'x' into our new list
>
> Thanks in advance, and keep up the good work. You guys are *really* making
> a difference.
>
> --
> Buy a copy of a baby naming book and you'll never be at a loss for
> variable names.
> - How To Write Unmaintainable Code
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Tom Jenkins
Development InfoStructure
http://www.devis.com