[Python-ideas] The non-obvious nature of str.join (was Re: sum(...) limitation)

Andrew Barnert abarnert at yahoo.com
Mon Aug 11 21:13:16 CEST 2014


On Aug 11, 2014, at 10:45, Stephen Hansen <me+python at ixokai.io> wrote:

> ... if the opposite of "string.split(sep)" were "list_of_strings.join(sep)" then that would mean that List  would have to know about how to combine strings. That's not very Pythonic.

I think the real problem here is that almost every OO language does it this way. Beginning programmers don't even know to look for a join function, so it doesn't matter where we put it. But someone coming to Python looking for the equivalent of -[NSArray componentsJoinedBySeparator:] or Enumerable#join or Sequence.joinStrings or whatever expects to find it as list.join. The fact that all of these other languages agreed on a stupid solution and Python on a more sensible one (in most of those languages, just as in Python, the enumeration/iteration/etc. protocol is a universal thing that every type already has to understand, while concatenating strings is something specific to strings) doesn't change the fact that they all agreed.

The question is whether this is more of a positive, as an opportunity to get people thinking Pythonically early instead of trying to write Ruby or C# code in Python, or a negative, as a stumbling block to them using the language.

Of course the obvious solution is to spell it like C++:

    stringstream ss;
    copy(a.begin(), a.end(), ostream_iterator(ss));
    s = ss.str();

Then nobody will find it at all, no matter what language they come from; problem solved. :)

> Also, Strings are immutable, that means:
> 
> str1 = str1 + str2
> 
> logically leads one to assume that it is constructing an entirely new string, copying the contents of str1 and str2 into it, and discarding the original str1. In fact, it did that for a long time. You can't change strings, after all. That is an fundamental tenet, and when people learn that they will get a new tool and think closer to idiomatic Python. Now, CPython has an optimization for this case which is the only reason the idea of sum(list_of_strings) is not largely fundamentally broken, but that's not a promise and not a feature of the language.
> 
> IMHO.
> 
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/


More information about the Python-ideas mailing list