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

StackOverflow https://stackoverflow.com/questions/22152668

  •  19-10-2022
  •  | 
  •  

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

Using the correct type is part of programming in Python. A general built-in like print does do the conversion (if the class supports __str__), which is where you should be doing it:

Let print do the work:

print(*myList, sep = " and ")

That's for Python 3, if you are still on Python 2 then use:

from __future__ import print_function
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top