2

Python: replacing all words found on a list

view story
linux-howto

http://www.linuxquestions.org – I've simplified the code, for the purpose of this example: Code: #!/usr/bin/env python # coding=utf-8-sig import re nouns = ['cow','cowboy'] text = 'thecowatethecowboy' for x in nouns:         if re.search(x, text):                 text = text.replace(x, 'NOUN') print text The result: theNOUNatetheNOUNboy Whereas I want: theNOUNatetheNOUN The fix I found was: Code: nouns = ['cowboy','cow'] This works in my short example, but for some mysterious reason, of which I am unable to discover, when implimented in my full code, the shorter items are still replaced first, thus I get the 'NOUNboy' problem. In other words, I can't seem to get this solution to work in my actual code, so I think I need a more robust solution. How can I guarantee that is will replace longer items first? (HowTos)