Why ' '.some_string is often used ?

Jacek Generowicz jacek.generowicz at cern.ch
Wed Jan 7 13:56:41 CET 2004


"Stéphane Ninin" <stefnin.nospam at yahoo.fr> writes:

>   Hi all,
> 
> This is not the first time I see this way of coding in Python and 
> I wonder why this is coded this way:
> 
> Howto on PyXML
> (http://pyxml.sourceforge.net/topics/howto/node14.html) 
> shows it on this function, but I saw that in many other pieces of code:
> 
> def normalize_whitespace(text):
>     "Remove redundant whitespace from a string"
>     return ' '.join(text.split())
> 
> Is there a reason to do instead of just returning join(text.split()) ?

One reason for preferring the former over the latter might be that the
former works, while the latter doesn't:


   >>> text = '   this   is   a   late   parrot  '
   >>> ' '.join(text.split())
   'this is a late parrot'
   >>> join(text.split())
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   NameError: name 'join' is not defined
   
You can make it work of course ...
   
   >>> from string import join
   >>> join(text.split())
   'this is a late parrot'

But you shouln't really be polluting your globals with stuff from
modules, so you'd probably prefer to

   import string

rather than

   from string import join

(or, heaver forbid

   from string import *

!)

In which case you would end up writing

   string.join(text.split())

which is a whole whopping 3 characters longer than

   ' '.join(text.split())

:-)

If you are too zealous in your interpretation of the second line of
the Zen of Python[*], then you might also prefer the latter as it is
more explicit than the former.




[*] try: 

   >>> import this



More information about the Python-list mailing list