How to turn a list/tuple into a space separated string in python using a single line?

寵の児 提交于 2020-02-03 04:46:25

问题


I tried doing:

str = ""
"".join(map(str, items))

but it says str object is not callable. Is this doable using a single line?


回答1:


Use string join() method.

List:

>>> l = ["a", "b", "c"]
>>> " ".join(l)
'a b c'
>>> 

Tuple:

>>> t = ("a", "b", "c")
>>> " ".join(t)
'a b c'
>>> 

Non-string objects:

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



回答2:


The problem is map need function as first argument.

Your code

str = ""
"".join(map(str, items))

Make str function as str variable which has empty string.

Use other variable name.




回答3:


Your map() call isn't working because you overwrote the internal str() function. If you hadn't done that, this works:

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

In [26]: "".join(map(str, items))
Out[26]: 'foobarbazquuxstuff'

Or, you could simply do:

In [27]: "".join(items)
Out[27]: 'foobarbazquuxstuff'

assuming items contains strings. If it contains ints, floats, etc., you'll need map().




回答4:


Try:

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


来源:https://stackoverflow.com/questions/28666951/how-to-turn-a-list-tuple-into-a-space-separated-string-in-python-using-a-single

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!