Rule of order for dot operators?

Thomas 'PointedEars' Lahn PointedEars at web.de
Sat May 16 15:40:08 EDT 2015


C.D. Reimer wrote:
^^^^
Who?

> Noobie

What?

> question regarding a single line of code that transforms a URL
> slug ("this-is-a-slug") into a title ("This Is A Slug").
> 
> title = slug.replace('-',' ').title()
> 
> This line also works if I switched the dot operators around.
> 
> title = slug.title().replace('-',' ')
> 
> I'm reading the first example as character replacement first and title
> capitalization second, and the second example as title capitalization
> first and character replacement second.

You are reading correctly.

> Does python perform the dot operators from left to right or according to
> a rule of order (i.e., multiplication/division before add/subtract)?

Yes.  If you debug the code, which you should have done before posting [1] , 
you will see that

  'this-is-a-slug'.title() == 'This-Is-A-Slug'

It follows that in this special case it does not matter if you call .title() 
before or after .replace().

However, for greater efficiency, in general you should call .replace() in 
such a way that the length of the string it operates on is minimized.  For 
example, if feasible, always slice *before* .replace().

[1] <http://www.catb.org/~esr/faqs/smart-questions.html>
 
-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.



More information about the Python-list mailing list