Matthew Jendrasiak Matthew Jendrasiak - 6 months ago 21
Python Question

Easy Way To Convert A List To A String, Still Formatted As A List

This should be quite simple but I can't find a simple solution. Frankly this should be a one liner.

In Python 3, how can you convert a list, such as


to a string that is formatted exactly the same, like


I don't wish to split it into two words.

// This is bad.
"hello world"

I want to keep the traditional list formatting. I initially thought you could just bind the list as a string like (str)list_name but apparently not. Is there not a simple function for this?


I found thanks to AChampion that it was a simple syntactical error. I was trying to bind a list to a string like this:

//this is bad

When I should have been writing it like this

//this is good

That gives me exactly what I was looking for. Thanks for the help and sorry I had to bring such a beginner question here. Still getting used to Python.


Both a lists str() and repr() forms are what you are asking for, assuming that the it is a list of simple strings.
If you have a more complicated structure and wish to transfer (serialize) to string form and back to object form you may want to look into the json module:

>>> import json
>>> json.dumps(['hello','world'])
'["hello", "world"]'