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

Caleb Hattingh caleb1 at telkomsa.net
Fri Nov 26 04:45:59 CET 2004


Wow, yeh, that's actually much better.

I got into python back when map, filter & lambda were still fashionable.   
The list comprehension is sweeter than the map, that's for sure.

> My solution would be:
>
>>>> keywords = ['my','is']
>>>> sentence = 'hi there my name is caleb'
>>>> lsen = sentence.split()
>>>> def myfunc(kw,word):
> ...     if word in kw:
> ...         return '*%s*' % word
> ...     else:
> ...         return word
> ...
>>>> ans = [ myfunc(keywords, word) for word in lsen ]
>>>> ans
> ['hi', 'there', '*my*', 'name', '*is*', 'caleb']
>>>> newSentence = ' '.join(ans)
>>>> newSentence
> 'hi there *my* name *is* caleb'
>
> Kind Regards
> Berthold




More information about the Python-list mailing list