Gotcha in replace
klausman at tuts.net
Sun Jul 8 14:06:36 CEST 2001
Tom Jenkins <tjenkins at devis.com> wrote:
> Hello all,
> 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.
> It was trivial for this script to work around the gotcha (I just put the
> replace in a loop and broke out when new string equalled the old
> string). But that method may not be an appropriate workaround in all cases.
> Is this known behavior and I just missed it; or is this a bug in replace?
I wouldn't call it a bug even if it's a gotcha. You're
replacing ,'', with ,' ', and then look for the next
occurence of ,'',. The search starts *after* what you
just replaced, therefore it doesn't match (there would
have to be something like ,'',,'', ).
Maybe a better replace-call would be:
y.replace(",''", ",' '")
By this, the next occurence should be found correctly.
More information about the Python-list