re. help needed :(

Jeff Shipman shippy at
Fri Feb 22 17:27:51 EST 2002

G. Willoughby wrote:
> Hi,
>     Im trying to replace the single word "lamb" and the word lamb followed
> by any punctuation in this string:
> x="Mary had a little lamb called lamb, but didn't like the lamb's mood"
> i want to replace all of the single words "lamb[punctuation]" but not the
> word "lamb's" to achieve this:
> x="Mary had a little pig called pig, but didn't like the lamb's mood"
> any help with be greatly appreiciated!
> ta
> G. Willoughby

x = re.sub('lamb(?!\')', 'pig', x)

should do the trick. This replaces all occurances
of lamb with pig only if it's not followed by an
apostrophe. If you want to look for more types
of punctuation, then you could use a [] to indicate
a set rather than the \'.

Jeff "Shippy" Shipman     E-Mail: shippy at
Computer Science Major    ICQ: 1786493
New Mexico Institute of Mining and Technology

More information about the Python-list mailing list