replace words
Scott David Daniels
scott.daniels at acm.org
Fri Oct 28 12:03:20 EDT 2005
Peter Otten wrote:
> 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
>
Perhaps you can use a variant of:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/231347
def wrap(source, pre, post):
gen = iter(source)
for portion in gen:
yield portion
try:
bracketed = gen.next()
except StopIteration:
break
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 acm.org
More information about the Python-list
mailing list