Python 3中的join()函数仅支持字符串?

时间:2015-07-17 08:50:00

标签: python

Python 3,Windows 7.我发现在Python 3中join()函数仅适用于字符串(What !? Why?)。我需要它来处理任何事情。

例如

lista = [1,2,3,"hey","woot",2.44]
print (" ".join(lista))

1 2 3 hey woot 2.44

也有人可以告诉我为什么它只支持字符串吗?

3 个答案:

答案 0 :(得分:3)

替代:

print (" ".join([str(x) for x in lista]))

但Anand S Kumar的版本更适合表演。

答案 1 :(得分:0)

它仅支持字符串,因为“”.join()的输出将采用字符串格式

lista = [1,2,3,"hey","woot",2.44]
print (" ".join(map(str,lista)))
print type(" ".join(map(str,lista)))
1 2 3 hey woot 2.44
<type 'str'>

这是因为你不能追加int / float和string:

即。)

"a"+2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-232-902dbc9d2568> in <module>()
----> 1 "a"+2

TypeError: cannot concatenate 'str' and 'int' objects 

lista = [1,2,3,"hey","woot",2.44]
print (" ".join(lista))

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-235-f57f2c8c638f> in <module>()
    1 lista = [1,2,3,"hey","woot",2.44]
----> 2 print (" ".join(lista))
    3 

TypeError: sequence item 0: expected string, int found 

完成加入后:

lista = [1,2,3,"hey","woot",2.44]
print (" ".join(lista))

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-235-f57f2c8c638f> in <module>()
    1 lista = [1,2,3,"hey","woot",2.44]
----> 2 print (" ".join(lista))
    3 

TypeError: sequence item 0: expected string, int found 

声明0索引处的元素是int而不是字符串参数

join将在内部执行的是它将遍历列表(可迭代对象)并在这种情况下附加前缀" " a space并提供字符串输出So finally "".join() does not support int/float

答案 2 :(得分:0)

  

有谁可以告诉我为什么它只支持字符串?

Python(2.x和3.x)动态但强类型,因此(与弱类型语言不同,其中'a' + 1将被隐式转换至'a' + '1',因此'a1')隐式类型转换根本不会发生:

>>> 'a' + 1

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    'a' + 1
TypeError: cannot concatenate 'str' and 'int' objects

请注意the documentation for str.join读取(强调我的):

  

返回一个字符串,该字符串是 iterable iterable 中字符串的串联

要解决此问题,您需要将元素显式转换为字符串,例如使用map

>>> ' '.join(map(str, [1, 2, 3, "hey", "woot", 2.44]))
'1 2 3 hey woot 2.44'