On Mon, 28 Dec 2009 17:35:22 -0800, Aahz wrote:

> In article <mailman.1744.1260564589.2873.python-l...@python.org>, Ed
> Keith  <e_...@yahoo.com> wrote:
>>
>>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.
> 
> What kind of guarantee do you have that the asterisk will only exist on
> the first and last character, if at all?

Does it matter?



In any case, surely the simplest solution is to eschew regular 
expressions and do it the easy way.


result = [s[1:-1] for s in l if s.startswith('*') and s.endswith('*')]


For a more general solution, I'd use a pair of helper functions:

def bracketed_by(s, prefix, suffix=None):
    if suffix is None:
        suffix = prefix
    return s.startswith(prefix) and s.endswith(suffix)

def strip_brackets(s, prefix, suffix=None):
    if suffix is None:
        suffix = prefix
    return s[len(prefix):-len(suffix)]

    
Note that I haven't tested these two helper functions. The second in 
particular may not work correctly in some corner cases (e.g. passing the 
empty string as suffix).



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to