Gotcha in replace

Tim Roberts timr at
Tue Jul 10 02:03:37 EDT 2001

Tom Jenkins <tjenkins at> wrote:
>While I was working on some database scripting, I got bit by this 
>behavior in replace.
> >>> y = "insert into blah values ('hello','','','','bye')"
> >>> y.replace(",'',", ",' ',")
>"insert into blah values ('hello',' ','',' ','bye')"
> >>>
>Notice that the second matching set of ",''," characters are not 
>replaced probably because the first and second matching sets overlap on 
>the last and first character, respectively.
>Is this known behavior and I just missed it; or is this a bug in replace?

It is known behavior.  The behavior makes more sense when you consider the
implementation of "replace"; it is essentially implemented as "split"
followed by "join":

  def replace(self,from,to):
    return to.join(self.split(from))
- Tim Roberts, timr at
  Providenza & Boekelheide, Inc.

More information about the Python-list mailing list