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

Thomas Guettler guettli at thomas-guettler.de
Thu Nov 25 10:34:59 EST 2004


Am Thu, 25 Nov 2004 15:43:53 +0100 schrieb Nico Grubert:

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

You can give re.sub() a function

import re
ignore=["and", "not", "or"]
test="test and testing and not perl or testit or example"
def repl(match):
    word=match.group(1)
    if word in ignore:
        return word
    else:
        return "*%s*" % word
print re.sub(r'(\w+)', repl, test)

Result: *test* and *testing* and not *perl* or *testit* or *example*

HTH,
 Thomas





More information about the Python-list mailing list