Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I tried doing:

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

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

like image 983
Joan Venge Avatar asked Feb 23 '15 04:02

Joan Venge


2 Answers

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'
>>> 
like image 166
Vivek Sable Avatar answered Sep 30 '22 15:09

Vivek Sable


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.

like image 20
Nilesh Avatar answered Sep 30 '22 14:09

Nilesh