replace words

Scott David Daniels scott.daniels at
Fri Oct 28 18:03:20 CEST 2005

Peter Otten wrote:
> hagai26 at 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\.)
>>"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
Perhaps you can use a variant of:

     def wrap(source, pre, post):
         gen = iter(source)
         for portion in gen:
             yield portion
                 bracketed =
             except StopIteration:
             yield pre
             yield bracketed
             yield post

     def mangledots(string):
         return ''.join(wrap(string.split('.'), '.start ', ' end.'))

print mangledots('been .taken.  it may be .left. there, '
                  'even if the .live coals were not. cleared')

--Scott David Daniels
scott.daniels at

More information about the Python-list mailing list