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?
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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With