I can't understand re.sub

Jussi Piitulainen harvesting at is.invalid
Mon Nov 30 03:51:13 EST 2015


Erik writes:

> On 29/11/15 21:36, Mr Zaug wrote:
>> This should be simple, right?
>
> It is. And it could be even simpler if you don't bother with regexes
> at all (if your input is as fixed as you say it is):
>
> >>> foo = "foo bar baz spam CONTENT_PATH bar spam"
> >>> ' Substitute '.join(foo.split(' CONTENT_PATH ', 1))
> 'foo bar baz spam Substitute bar spam'

Surely the straight thing to say is:

   >>> foo.replace(' CONTENT_PATH ', ' Substitute ')
   'foo bar baz spam Substitute bar spam'

But there was no guarantee of spaces around the target. If you wish to,
say, replace "spam" in your foo with "REDACTED" but leave it intact in
"May the spammer be prosecuted", a regex might be attractive after all.



More information about the Python-list mailing list