我们有一个列表:
myList = [1, "two"]
并且想要打印出来,通常我会使用类似的东西:
"{0} and {1}".format(*myList)
但你也可以这样做:
" and ".join(myList)
但不幸的是:
>>> " and ".join(myList)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
为什么它不自动将接收到的列表转换为字符串?
什么时候不需要它来将它们转换为字符串?我是否遗漏了一些微小的边缘情况?
最佳答案
来自Zen of Python :
Explicit is better than implicit.
和
Errors should never pass silently.
隐式转换为字符串可以很容易地隐藏错误,我真的很想知道我是否突然在某个地方有不同的类型,这些类型本来是字符串。
如果你想明确地转换成字符串,你可以使用map()
,例如:
''.join(map(str, myList))
关于python - 为什么 join() 不自动将其参数转换为字符串?你什么时候不想让它们成为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22152668/