a list/re problem

Matt Nordhoff mnordhoff at mattnordhoff.com
Fri Dec 11 19:21:10 EST 2009


Grant Edwards wrote:
> On 2009-12-11, Ed Keith <e_d_k at yahoo.com> wrote:
>> I have a problem and I am trying to find a solution to it that is both 
>> efficient and elegant.
>>
>> I have a list call it 'l':
>>
>> l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr']
> 
>> Notice that some of the items in the list start and end with
>> an '*'. I wish to construct a new list, call it 'n' which is
>> all the members of l that start and end with '*', with the
>> '*'s removed.
>>
>> So in the case above n would be ['nbh', 'jkjsdfjasd']
> 
> [s[1:-1] for s in l if (s[0] == s[-1] == '*')]

s[0] and s[-1] raise an IndexError if l contains an empty string.

Better something like:

>>> [s[1:-1] for s in l if (s[:1] == s[-1:] == '*')]

Or just the slightly more verbose startswith/endswith version.
-- 
Matt Nordhoff



More information about the Python-list mailing list