[Tutor] Can re do this?
Kent Johnson
kent_johnson at skillsoft.com
Mon Aug 30 18:05:02 CEST 2004
Alan,
Can you just replace "the lazy dog" with "the xxx dog" in one operation
using re.sub()?
>>> s="the quick fox jumped over the lazy dog's back"
>>> re.sub("the lazy dog", "the xxx dog", s)
"the quick fox jumped over the xxx dog's back"
If your real requirements are more complex than what you have described,
maybe re.sub() with a function as the repl parameter would work - this
allows you to do whatever computation you need to get the replacement
string. For example to replace "lazy" with the value of a counter:
>>> count = 0
>>> def myRepl(match):
... global count
... count += 1
... return match.group(0).replace('lazy', str(count))
...
>>> import re
>>> re.sub("the lazy dog", myRepl, s)
"the quick fox jumped over the 1 dog's back"
>>> re.sub("the lazy dog", myRepl, s)
"the quick fox jumped over the 2 dog's back"
>>> re.sub("the lazy dog", myRepl, s)
"the quick fox jumped over the 3 dog's back"
>>>
At 11:43 AM 8/30/2004 -0400, R. Alan Monroe wrote:
>Given a test file like:
>The quick brown fox jumps over the lazy log
>Another test line lazy dog
>
>I want to match lines containing "the lazy dog" (line 2 would not
>match). This I can do. I then want to change "lazy" to "xxx" (in line
>1 but not line 2). This is where I'm getting stuck. I can't figure out
>how to replace just a subset of "the lazy dog", which is itself, a
>subset of the entire line.
>
>Alan
>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list