Replacing words from strings except 'and' / 'or' / 'and not'

Alexandre Cecchi a.cecchi at gmail.com
Thu Nov 25 13:52:46 EST 2004


> Hi there,
> 
> Background of this question is:
> I want to convert all words <word> except 'and' / 'or' / 'and not' from
> a string into '*<word>*'.

Hello,

def do(s):
    L = []
    for x in s.split():
        if x in ('or','and'):
            L.append(x)    
        elif x == 'not' and L and L[-1] == 'and':
            L.append('not')
        else:
            L.append("'*%s*'" % x)
    return ' '.join(L)

I think that it is more readable, maybe not faster, elegant I don't know =)
print 'Yeahh it was my first post on the list.'

bye.



More information about the Python-list mailing list