Implicit conversion to str in str.join method?

Chris Angelico rosuav at gmail.com
Mon Feb 26 14:43:04 EST 2018


On Tue, Feb 27, 2018 at 6:38 AM, Kirill Balunov <kirillbalunov at gmail.com> wrote:
> Currently `str.join` raises `TypeError` if there are any non-string values
> in iterable, including `bytes` objects. Is it an awful idea to implicitly
> _cast_ elements in iterable to their `str` or `repr` representation? Was
> this question adressed before?
>
> As for me there are two valid points: On one hand "Explicit is beter than
> implicit" and on the other "Practicality beats purity". May be I'm the only
> one who finds that it is rather boring to write somehting like:
>
>     ", ".join(str(i) for i in iterable)
>
> when iterable contains non-string values, instead of:
>
>     ", ".join(iterable)
>
> I don't know how much overhead will yield for the case when iterable
> contains only strings...and if it is possible to optimize this case. This
> change is backward compatible, but as I wrote above, it can be perceived
> badly and yield a huge overhead for general case that it is not even worth
> discussing. What do you think?

This would be a perfect job for map.

", ".join(map(str, iterable))

If this is for display, you could also just print the values directly:

print(*iterable, sep=", ")

ChrisA



More information about the Python-list mailing list