Why " ".some_string is often used ?

John Roth newsgroups at jhrothjr.com
Thu Jan 8 12:42:11 CET 2004


"Stéphane Ninin" <stefnin.nospam at yahoo.fr> wrote in message
news:Xns94698A5566736stefninnospamyahoofr at 213.228.0.4...
>
>   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()) ?
> why concatenate " " to the string and not just returning the string
instead ?

This particular idiom replaces sequences of multiple whitespace
charaters with a single blank.

And I agree, it's not entirely obvious why it's a string
method rather than a list method, since it operates on
a list, not on a string. The only explanation that makes
sense is that, as a list method, it would fail if the list
contained something other than a string. That's still
not very friendly, though.

John Roth
>
> Thanks in advance for your explanations.
>
>   Regards,
>
> -- 
> Stephane Ninin
>
>
>





More information about the Python-list mailing list