Conversion of Strings to list
<p>Can someone please help me with a simple code that returns a list as an output to list converted to string? The list is NOT like this:</p>

<pre><code>a = u"['a','b','c']"
</code></pre>

<p>but the variable is like this: </p>

<pre><code>a = '[a,b,c]'
</code></pre>

<p>So,</p>

<pre><code>list(a)
</code></pre>

<p>would yield the following output</p>

<pre><code>['[', 'a', ',', 'b', ',', 'c', ']']
</code></pre>

<p>instead I want the input to be like this:</p>

<pre><code>['a', 'b', 'c']  
</code></pre>

<p>I have even tried using the <code>ast.literal_eval()</code> function - on using which I got a <code>ValueError</code> exception stating the argument is a malformed string.</p>

<p>There is no standard library that'll load such a list. But you can trivially do this with string processing:</p>

<pre><code>a.strip('[]').split(',')
</code></pre>

<p>would give you your list.</p>

<p><code>str.strip()</code> will remove <em>any</em> of the given characters from the start and end; so it'll remove any and all <code>[</code> and <code>]</code> characters from the start until no such characters are found anymore, then remove the same characters from the end. That suffices nicely for your input sample.</p>

<p><code>str.split()</code> then splits the remainder (minus the <code>[</code> and <code>]</code> characters at either end) into separate strings at any point there is a comma:</p>

<pre><code>&gt;&gt;&gt; a = '[a,b,c]'
&gt;&gt;&gt; a.strip('[]')
'a,b,c'
&gt;&gt;&gt; a.strip('[]').split(',')
['a', 'b', 'c']
</code></pre>

python python-2.7