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>Let us use hack.</p>

<pre><code>import string

x = "[a,b,c]"

for char in x:
    if char in string.ascii_lowercase:
        x = x.replace(char, "'%s'" % char)

# Now x is "['a', 'b', 'c']"
lst = eval(x)
</code></pre>

<p>This checks if a character is in the alphabet(lowercase) if it is, it replaces it with a character with single quotes around it.</p>

<p><strong>Why not use this solution ?:</strong></p>

<ul>
<li>Fails for duplicate elements</li>
<li>Fails for elements with more than single characters.</li>
<li>You need to be careful about confusing single quote and double quotes</li>
</ul>

<p><strong>Why use this solution ?:</strong></p>

<ul>
<li>There are no reasons to use this solution rather than Martijn's. But it was fun coding it anyway.</li>
</ul>

<p>I wish you luck in your problem.</p>

python python-2.7