Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't join() automatically convert its arguments to strings? When would you ever not want them to be strings?

We have a list:

myList = [1, "two"]

And want to print it out, normally I would use something like:

"{0} and {1}".format(*myList)

But you could also do:

" and ".join(myList)

But unfortunately:

>>> " and ".join(myList)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found

Why doesn't it just automatically convert the list it receives to strings?

When would you ever not need it to convert them to strings? Is there some tiny edge case I'm missing?

like image 700
LittleBobbyTables Avatar asked Mar 03 '14 16:03

LittleBobbyTables


2 Answers

From the Zen of Python:

Explicit is better than implicit.

and

Errors should never pass silently.

Converting to strings implicitly can easily hide bugs, and I'd really want to know if I suddenly have different types somewhere that were meant to be strings.

If you want to explicitly convert to strings, you can do so using map(), for example:

''.join(map(str, myList))
like image 76
Martijn Pieters Avatar answered Oct 09 '22 11:10

Martijn Pieters


The problem with attempting to execute something like x = 4 + "8" as written is that the intended meaning is ambiguous. Should x contain "48" (implicitly converting 4 to str) or 12 (implicitly converting "8" to int)? We can't justify either result.

To avoid this confusion, Python requires explicit conversion of one of the operands:

>>> x = str(4) + "8"
>>> y = 4 + int("8")
>>> print x
48
>>> print y
12
like image 23
Tetrinity Avatar answered Oct 09 '22 11:10

Tetrinity