[Python-ideas] strings as iterables - from str.startswith taking any iterator instead of just tuple

Steven D'Aprano steve at pearwood.info
Sat Jan 4 23:59:04 CET 2014


On Sat, Jan 04, 2014 at 11:22:16AM +0100, spir wrote:
> On 01/03/2014 07:11 PM, Bruce Leban wrote:
> >As to the idea of making strings not iterable, that would break my code. I
> >write a lot of code to manipulate words (to create puzzles) and iterating
> >over strings is fundamental. In fact, I'd like to have strings as results
> >of iteration operations on strings:
> >
> >>>>>>>sorted('string')
> >'ginrst'
> >>>>>>>list(itertools.permutations('bar'))
> >['bar', 'bra', 'abr', 'arb', 'rba', 'rab']

That would be nice to have.


> >instead I have to write
> >
> >>>>>>>''.join(sorted('string'))
> >>>>>>>[''.join(s) for s in itertools.permutations('bar')]

Which is a slight inconvenience, but not a great one. You can always 
save three characters by creating a helper function:

join = ''.join


> Maybe we just need a 'cat' or 'concat' [1] method for lists:
>    sorted('string').cat()
>    (s for s in itertools.permutations('bar')).cat()

-1

Lists are general collections, giving them a method that depends on a 
specific kind of item is ugly. Adding that same method to generator 
expressions is even worse. We don't have list.sum() for adding lists of 
numbers, we have a sum() function that takes a list.


> (Then, a hard choice: should cat crash when items are not strings, or 
> automagically stringify its operands? I wish join would do the latter.)

-1

Joining what you think is a list of strings but actually isn't is an 
error. The right thing to do in the face of an error is to raise an 
exception, not to silently hide the error. If you want to 
automatically convert arbitrary items into strings, it is better to 
explicitly do so:

''.join(str(x) for x in items)

than to have it magically, and incorrectly, happen implicitly.


> [1] I have not understood yet why "concatenation", instead of just 
> "catenation". Literaly means chaining (things) together; but I'm still 
> trying to figure out how one can chain things apart ;-)

Chain your left arm to the wall on your left, and your right arm to the 
wall on your right. Your arms are now chained apart.

http://www.vlvstamps.com/man-chained-to-wall.html

(Safe for work.)



-- 
Steven


More information about the Python-ideas mailing list