如何在python中使用一行代码将列表/元组转换为空格分隔的字符串?

如何在python中使用一行代码将列表/元组转换为空格分隔的字符串?,python,string,collections,formatting,string-formatting,Python,String,Collections,Formatting,String Formatting,我试着做: str = "" "".join(map(str, items)) 但它说str对象是不可调用的。这可以用一行实现吗?使用stringjoin()方法 名单: 元组: >>> t = ("a", "b", "c") >>> " ".join(t) 'a b c' >>> 非字符串对象: >>> l = [1,2,3] >>> " ".join([str(i) for i in l]) '1

我试着做:

str = ""
"".join(map(str, items))
但它说str对象是不可调用的。这可以用一行实现吗?

使用string
join()
方法

名单:

元组:

>>> t = ("a", "b", "c")
>>> " ".join(t)
'a b c'
>>> 
非字符串对象:

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

问题是
map
需要函数作为第一个参数

你的代码

str = ""
"".join(map(str, items))
使
str
作为具有空字符串的
str
变量运行

使用其他变量名。

您的
map()
调用无效,因为您重写了内部
str()
函数。如果您没有这样做,这是可行的:

In [25]: items = ["foo", "bar", "baz", "quux", "stuff"]

In [26]: "".join(map(str, items))
Out[26]: 'foobarbazquuxstuff'
或者,您可以简单地执行以下操作:

In [27]: "".join(items)
Out[27]: 'foobarbazquuxstuff'
假设
包含字符串。如果它包含
int
s、
float
s等,则需要
map()

尝试:

>>> items=[1, 'a', 2.3, (1, 2)]
>>> ' '.join(str(i) for i in items)
'1 a 2.3 (1, 2)'

“”.join(映射(str,items))?不要将
str
重新分配给任何对象,它是Python中的内置函数和类型。
>>> items=[1, 'a', 2.3, (1, 2)]
>>> ' '.join(str(i) for i in items)
'1 a 2.3 (1, 2)'