Double replace or single re.sub?

Bengt Richter bokr at oz.net
Fri Oct 28 04:13:59 CEST 2005


On 27 Oct 2005 12:39:18 -0700, "EP" <eric.pederson at gmail.com> wrote:

>How does Python execute something like the following
>
>oldPhrase="My dog has fleas on his knees"
>newPhrase=oldPhrase.replace("fleas",
>"wrinkles").replace("knees","face")
>
>Does it do two iterations of the replace method on the initial and then
>an intermediate string (my guess) -- or does it compile to something
>more efficient (I doubt it, unless it's Christmas in Pythonville... but
>I thought I'd query)
>
Here's a way to get an answer in one form:

 >>> def foo(): # for easy disassembly
 ...    oldPhrase="My dog has fleas on his knees"
 ...    newPhrase=oldPhrase.replace("fleas",
 ...    "wrinkles").replace("knees","face")
 ...
 >>> import dis
 >>> dis.dis(foo)
   2           0 LOAD_CONST               1 ('My dog has fleas on his knees')
               3 STORE_FAST               1 (oldPhrase)

   3           6 LOAD_FAST                1 (oldPhrase)
               9 LOAD_ATTR                1 (replace)
              12 LOAD_CONST               2 ('fleas')

   4          15 LOAD_CONST               3 ('wrinkles')
              18 CALL_FUNCTION            2
              21 LOAD_ATTR                1 (replace)
              24 LOAD_CONST               4 ('knees')
              27 LOAD_CONST               5 ('face')
              30 CALL_FUNCTION            2
              33 STORE_FAST               0 (newPhrase)
              36 LOAD_CONST               0 (None)
              39 RETURN_VALUE

Regards,
Bengt Richter



More information about the Python-list mailing list