replace words

Peter Otten __peter__ at web.de
Wed Oct 26 11:40:40 CEST 2005


hagai26 at gmail.com wrote:

> What is the way for replacing in a string from . to . the sentence?
> for example:
> "been .taken.  it may be .left. there,
> even if the .live coals were not. cleared"
> I want to do this-> replace(\.(.*)\.,\.start (1) end\.)
> result:
> "been .start taken end.  it may be .start left end. there,
> even if the .start live coals were not end. cleared"

Use \1 to refer to the group in the substitution expression.
You also need to change the regex to non-greedy match (the trailing ?).
Otherwise you only get one big match from .taken ... not.

import re
s = ("been .taken.  it may be .left. there, "
     "even if the .live coals were not. cleared")

r = re.compile(r"\.(.*?)\.")
print r.sub(r".start \1 end.", s)

Peter




More information about the Python-list mailing list