如何使用单行将list/tuple转换为python中的空格分隔字符串?

Joa*_*nge 7 python string collections formatting string-formatting

我试过做:

str = ""
"".join(map(str, items))
Run Code Online (Sandbox Code Playgroud)

但它说str对象不可调用.这可以使用一条线吗?

Viv*_*ble 7

使用字符串join()方法.

列表:

>>> l = ["a", "b", "c"]
>>> " ".join(l)
'a b c'
>>> 
Run Code Online (Sandbox Code Playgroud)

元组:

>>> t = ("a", "b", "c")
>>> " ".join(t)
'a b c'
>>> 
Run Code Online (Sandbox Code Playgroud)

非字符串对象:

>>> l = [1,2,3]
>>> " ".join([str(i) for i in l])
'1 2 3'
>>> " ".join(map(str, l))
'1 2 3'
>>> 
Run Code Online (Sandbox Code Playgroud)