tags:

views:

138

answers:

2

Hello!

I want to format a list into a string in this way: [1,2,3] => '1 2 3'. How to do this? Is there any customizable formatter in Python as Common Lisp format?

+11  A: 
' '.join(str(i) for i in your_list)
SilentGhost
Oh, thanks! I forgot about this way..
Anton Kazennikov
That would be great ... if it worked !!! If you list contains anything that's not a string, this line will fail with the error:Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: sequence item 0: expected string, int found
PierreBdR
'{0} {1} {2}'.format(your_list) solves the problem too. The point is that you need to do join on a separator. I cannot possibly believe that OP needs actual representation of [1,2,3] list.
SilentGhost
In my opinion, for the sake of correctness, and for beginners that will seek answer on this website, you should always post code that works, or at least say what need to be done to make it work.
PierreBdR
+7  A: 
' '.join(str(i) for i in your_list)

First, convert any element into a string, then join them into a unique string.

PierreBdR
+1 you can also use ' '.join(map(str, your_list))
Nadia Alramli
@Nadia: Yes, but that is discouraged, list comprehensions are the recommended way.
nikow