2024-05-29 05:54:20 发布
网友
Python 3,Windows 7。我发现在Python3中,join()函数只对字符串有效(什么!?为什么?)。我需要它来处理任何事情。在
join()
例如
lista = [1,2,3,"hey","woot",2.44] print (" ".join(lista)) 1 2 3 hey woot 2.44
还有谁能告诉我为什么它只支持字符串吗?在
备选方案:
print (" ".join([str(x) for x in lista]))
但阿南德库马尔的版本更适合于表演。在
Python(2.x和3.x)是动态但强类型的,因此(不像弱类型语言,'a' + 1将隐式转换为'a' + '1',因此{})隐式类型转换不会发生:
'a' + 1
'a' + '1'
>>> '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 ^{}的内容是(emphasis mine):
Return a string which is the concatenation of the strings in the iterable iterable.
要解决这个问题,您需要将元素显式地转换为字符串,例如使用^{}:
它只支持字符串,因为“.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:
即)
完成连接后:
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将遍历列表(iterable对象),并在本例中添加前缀" " a space,并提供一个字符串输出So finally "".join() does not support int/float
join
" " a space
So finally "".join() does not support int/float
备选方案:
但阿南德库马尔的版本更适合于表演。在
Python(2.x和3.x)是动态但强类型的,因此(不像弱类型语言,})隐式类型转换不会发生:
'a' + 1
将隐式转换为'a' + '1'
,因此{请注意,the documentation for ^{} 的内容是(emphasis mine):
要解决这个问题,您需要将元素显式地转换为字符串,例如使用^{} :
^{pr2}$它只支持字符串,因为“.join()的输出将采用字符串格式:
这是因为您不能附加int/float和string:
即)
^{pr2}$完成连接后:
它声明索引0处的元素是int而不是字符串参数
在内部,
join
将遍历列表(iterable对象),并在本例中添加前缀" " a space
,并提供一个字符串输出So finally "".join() does not support int/float
相关问题 更多 >
编程相关推荐