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

Skip Montanaro skip at pobox.com
Thu Nov 25 10:27:27 EST 2004


    Nico> Example:
    Nico> I have the following string: 
    Nico> "test and testing and not perl or testit or example"

    Nico> I want to convert this string to:
    Nico> '*test*' and '*testing*' and not '*perl*' or '*testit*' or '*example*'

    Nico> Any idea, how to do this?

Here's my shot at it:

    def decorate(s):
        words = s.split()
        # make "and not" a 'word'
        for i in range(len(words)-1,-1,-1):
            if words[i] == 'and' and words[i+1] == 'not':
                words[i:i+2] = ["and not"]
        special = ('and', 'and not', 'or')
        for word in words:
            if word in special:
                yield word
            else:
                yield "*%s*" % word

    s = "test and testing and not perl or testit or example"
    print " ".join(decorate(s))

Hoping I didn't just do your homework, I wish you a Happy Thanksgiving...

Skip



More information about the Python-list mailing list