How to convert string representation of list to a list

I was wondering what the simplest way is to convert a string representation of a list like the following to a list:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>x = '[ "A","B","C" , " D"]'
</code>
<code>x = '[ "A","B","C" , " D"]' </code>
x = '[ "A","B","C" , " D"]'

Even in cases where the user puts spaces in between the commas, and spaces inside of the quotes, I need to handle that as well and convert it to:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>x = ["A", "B", "C", "D"]
</code>
<code>x = ["A", "B", "C", "D"] </code>
x = ["A", "B", "C", "D"] 

I know I can strip spaces with strip() and split() and check for non-letter characters. But the code was getting very kludgy. Is there a quick function that I’m not aware of?

0

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> import ast
>>> x = '[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']
</code>
<code>>>> import ast >>> x = '[ "A","B","C" , " D"]' >>> x = ast.literal_eval(x) >>> x ['A', 'B', 'C', ' D'] >>> x = [n.strip() for n in x] >>> x ['A', 'B', 'C', 'D'] </code>
>>> import ast
>>> x = '[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']

ast.literal_eval:

Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.

This can be used for evaluating strings containing Python values without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

6

The json module is a better solution whenever there is a stringified list of dictionaries. The json.loads(your_data) function can be used to convert it to a list.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> import json
>>> x = '[ "A","B","C" , " D"]'
>>> json.loads(x)
['A', 'B', 'C', ' D']
</code>
<code>>>> import json >>> x = '[ "A","B","C" , " D"]' >>> json.loads(x) ['A', 'B', 'C', ' D'] </code>
>>> import json
>>> x = '[ "A","B","C" , " D"]'
>>> json.loads(x)
['A', 'B', 'C', ' D']

Similarly

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> x = '[ "A","B","C" , {"D":"E"}]'
>>> json.loads(x)
['A', 'B', 'C', {'D': 'E'}]
</code>
<code>>>> x = '[ "A","B","C" , {"D":"E"}]' >>> json.loads(x) ['A', 'B', 'C', {'D': 'E'}] </code>
>>> x = '[ "A","B","C" , {"D":"E"}]'
>>> json.loads(x)
['A', 'B', 'C', {'D': 'E'}]

5

The eval is dangerous – you shouldn’t execute user input.

If you have 2.6 or newer, use ast instead of eval:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> import ast
>>> ast.literal_eval('["A","B" ,"C" ," D"]')
["A", "B", "C", " D"]
</code>
<code>>>> import ast >>> ast.literal_eval('["A","B" ,"C" ," D"]') ["A", "B", "C", " D"] </code>
>>> import ast
>>> ast.literal_eval('["A","B" ,"C" ," D"]')
["A", "B", "C", " D"]

Once you have that, strip the strings.

If you’re on an older version of Python, you can get very close to what you want with a simple regular expression:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> x='[ "A", " B", "C","D "]'
>>> re.findall(r'"s*([^"]*?)s*"', x)
['A', 'B', 'C', 'D']
</code>
<code>>>> x='[ "A", " B", "C","D "]' >>> re.findall(r'"s*([^"]*?)s*"', x) ['A', 'B', 'C', 'D'] </code>
>>> x='[  "A",  " B", "C","D "]'
>>> re.findall(r'"s*([^"]*?)s*"', x)
['A', 'B', 'C', 'D']

This isn’t as good as the ast solution, for example it doesn’t correctly handle escaped quotes in strings. But it’s simple, doesn’t involve a dangerous eval, and might be good enough for your purpose if you’re on an older Python without ast.

2

Inspired from some of the answers above that work with base Python packages I compared the performance of a few (using Python 3.7.3):

Method 1: ast

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import ast
list(map(str.strip, ast.literal_eval(u'[ "A","B","C" , " D"]')))
# ['A', 'B', 'C', 'D']
import timeit
timeit.timeit(stmt="list(map(str.strip, ast.literal_eval(u'[ "A","B","C" , " D"]')))", setup='import ast', number=100000)
# 1.292875313000195
</code>
<code>import ast list(map(str.strip, ast.literal_eval(u'[ "A","B","C" , " D"]'))) # ['A', 'B', 'C', 'D'] import timeit timeit.timeit(stmt="list(map(str.strip, ast.literal_eval(u'[ "A","B","C" , " D"]')))", setup='import ast', number=100000) # 1.292875313000195 </code>
import ast

list(map(str.strip, ast.literal_eval(u'[ "A","B","C" , " D"]')))
# ['A', 'B', 'C', 'D']

import timeit
timeit.timeit(stmt="list(map(str.strip, ast.literal_eval(u'[ "A","B","C" , " D"]')))", setup='import ast', number=100000)
# 1.292875313000195

Method 2: json

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import json
list(map(str.strip, json.loads(u'[ "A","B","C" , " D"]')))
# ['A', 'B', 'C', 'D']
import timeit
timeit.timeit(stmt="list(map(str.strip, json.loads(u'[ "A","B","C" , " D"]')))", setup='import json', number=100000)
# 0.27833264000014424
</code>
<code>import json list(map(str.strip, json.loads(u'[ "A","B","C" , " D"]'))) # ['A', 'B', 'C', 'D'] import timeit timeit.timeit(stmt="list(map(str.strip, json.loads(u'[ "A","B","C" , " D"]')))", setup='import json', number=100000) # 0.27833264000014424 </code>
import json
list(map(str.strip, json.loads(u'[ "A","B","C" , " D"]')))
# ['A', 'B', 'C', 'D']

import timeit
timeit.timeit(stmt="list(map(str.strip, json.loads(u'[ "A","B","C" , " D"]')))", setup='import json', number=100000)
# 0.27833264000014424

Method 3: no import

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>list(map(str.strip, u'[ "A","B","C" , " D"]'.strip('][').replace('"', '').split(',')))
# ['A', 'B', 'C', 'D']
import timeit
timeit.timeit(stmt="list(map(str.strip, u'[ "A","B","C" , " D"]'.strip('][').replace('"', '').split(',')))", number=100000)
# 0.12935059100027502
</code>
<code>list(map(str.strip, u'[ "A","B","C" , " D"]'.strip('][').replace('"', '').split(','))) # ['A', 'B', 'C', 'D'] import timeit timeit.timeit(stmt="list(map(str.strip, u'[ "A","B","C" , " D"]'.strip('][').replace('"', '').split(',')))", number=100000) # 0.12935059100027502 </code>
list(map(str.strip, u'[ "A","B","C" , " D"]'.strip('][').replace('"', '').split(',')))
# ['A', 'B', 'C', 'D']

import timeit
timeit.timeit(stmt="list(map(str.strip, u'[ "A","B","C" , " D"]'.strip('][').replace('"', '').split(',')))", number=100000)
# 0.12935059100027502

I was disappointed to see what I considered the method with the worst readability was the method with the best performance… there are trade-offs to consider when going with the most readable option… for the type of workloads I use Python for I usually value readability over a slightly more performant option, but as usual it depends.

2

There is a quick solution:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>x = eval('[ "A","B","C" , " D"]')
</code>
<code>x = eval('[ "A","B","C" , " D"]') </code>
x = eval('[ "A","B","C" , " D"]')

Unwanted whitespaces in the list elements may be removed in this way:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>x = [x.strip() for x in eval('[ "A","B","C" , " D"]')]
</code>
<code>x = [x.strip() for x in eval('[ "A","B","C" , " D"]')] </code>
x = [x.strip() for x in eval('[ "A","B","C" , " D"]')]

3

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import ast
l = ast.literal_eval('[ "A","B","C" , " D"]')
l = [i.strip() for i in l]
</code>
<code>import ast l = ast.literal_eval('[ "A","B","C" , " D"]') l = [i.strip() for i in l] </code>
import ast
l = ast.literal_eval('[ "A","B","C" , " D"]')
l = [i.strip() for i in l]

If it’s only a one dimensional list, this can be done without importing anything:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> x = u'[ "A","B","C" , " D"]'
>>> ls = x.strip('[]').replace('"', '').replace(' ', '').split(',')
>>> ls
['A', 'B', 'C', 'D']
</code>
<code>>>> x = u'[ "A","B","C" , " D"]' >>> ls = x.strip('[]').replace('"', '').replace(' ', '').split(',') >>> ls ['A', 'B', 'C', 'D'] </code>
>>> x = u'[ "A","B","C" , " D"]'
>>> ls = x.strip('[]').replace('"', '').replace(' ', '').split(',')
>>> ls
['A', 'B', 'C', 'D']

2

There isn’t any need to import anything or to evaluate. You can do this in one line for most basic use cases, including the one given in the original question.

One liner

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>l_x = [i.strip() for i in x[1:-1].replace('"',"").split(',')]
</code>
<code>l_x = [i.strip() for i in x[1:-1].replace('"',"").split(',')] </code>
l_x = [i.strip() for i in x[1:-1].replace('"',"").split(',')]

Explanation

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>x = '[ "A","B","C" , " D"]'
# String indexing to eliminate the brackets.
# Replace, as split will otherwise retain the quotes in the returned list
# Split to convert to a list
l_x = x[1:-1].replace('"',"").split(',')
</code>
<code>x = '[ "A","B","C" , " D"]' # String indexing to eliminate the brackets. # Replace, as split will otherwise retain the quotes in the returned list # Split to convert to a list l_x = x[1:-1].replace('"',"").split(',') </code>
x = '[ "A","B","C" , " D"]'
# String indexing to eliminate the brackets.
# Replace, as split will otherwise retain the quotes in the returned list
# Split to convert to a list
l_x = x[1:-1].replace('"',"").split(',')

Outputs:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>for i in range(0, len(l_x)):
print(l_x[i])
# vvvv output vvvvv
'''
A
B
C
D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4
</code>
<code>for i in range(0, len(l_x)): print(l_x[i]) # vvvv output vvvvv ''' A B C D ''' print(type(l_x)) # out: class 'list' print(len(l_x)) # out: 4 </code>
for i in range(0, len(l_x)):
    print(l_x[i])
# vvvv output vvvvv
'''
 A
B
C
  D
'''
print(type(l_x)) # out: class 'list'
print(len(l_x)) # out: 4

You can parse and clean up this list as needed using list comprehension.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>l_x = [i.strip() for i in l_x] # list comprehension to clean up
for i in range(0, len(l_x)):
print(l_x[i])
# vvvvv output vvvvv
'''
A
B
C
D
'''
</code>
<code>l_x = [i.strip() for i in l_x] # list comprehension to clean up for i in range(0, len(l_x)): print(l_x[i]) # vvvvv output vvvvv ''' A B C D ''' </code>
l_x = [i.strip() for i in l_x] # list comprehension to clean up
for i in range(0, len(l_x)):
    print(l_x[i])
# vvvvv output vvvvv
'''
A
B
C
D
'''

Nested lists

If you have nested lists, it does get a bit more annoying. Without using regex (which would simplify the replace), and assuming you want to return a flattened list (and the zen of python says flat is better than nested):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>x = '[ "A","B","C" , " D", ["E","F","G"]]'
l_x = x[1:-1].split(',')
l_x = [i
.replace(']', '')
.replace('[', '')
.replace('"', '')
.strip() for i in l_x
]
# returns ['A', 'B', 'C', 'D', 'E', 'F', 'G']
</code>
<code>x = '[ "A","B","C" , " D", ["E","F","G"]]' l_x = x[1:-1].split(',') l_x = [i .replace(']', '') .replace('[', '') .replace('"', '') .strip() for i in l_x ] # returns ['A', 'B', 'C', 'D', 'E', 'F', 'G'] </code>
x = '[ "A","B","C" , " D", ["E","F","G"]]'
l_x = x[1:-1].split(',')
l_x = [i
    .replace(']', '')
    .replace('[', '')
    .replace('"', '')
    .strip() for i in l_x
]
# returns ['A', 'B', 'C', 'D', 'E', 'F', 'G']

If you need to retain the nested list it gets a bit uglier, but it can still be done just with regular expressions and list comprehension:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import re
x = '[ "A","B","C" , " D", "["E","F","G"]","Z", "Y", "["H","I","J"]", "K", "L"]'
# Clean it up so the regular expression is simpler
x = x.replace('"', '').replace(' ', '')
# Look ahead for the bracketed text that signifies nested list
l_x = re.split(r',(?=[[A-Za-z0-9',]+])|(?<=]),', x[1:-1])
print(l_x)
# Flatten and split the non nested list items
l_x0 = [item for items in l_x for item in items.split(',') if not '[' in items]
# Convert the nested lists to lists
l_x1 = [
i[1:-1].split(',') for i in l_x if '[' in i
]
# Add the two lists
l_x = l_x0 + l_x1
</code>
<code>import re x = '[ "A","B","C" , " D", "["E","F","G"]","Z", "Y", "["H","I","J"]", "K", "L"]' # Clean it up so the regular expression is simpler x = x.replace('"', '').replace(' ', '') # Look ahead for the bracketed text that signifies nested list l_x = re.split(r',(?=[[A-Za-z0-9',]+])|(?<=]),', x[1:-1]) print(l_x) # Flatten and split the non nested list items l_x0 = [item for items in l_x for item in items.split(',') if not '[' in items] # Convert the nested lists to lists l_x1 = [ i[1:-1].split(',') for i in l_x if '[' in i ] # Add the two lists l_x = l_x0 + l_x1 </code>
import re

x = '[ "A","B","C" , " D", "["E","F","G"]","Z", "Y", "["H","I","J"]", "K", "L"]'
# Clean it up so the regular expression is simpler
x = x.replace('"', '').replace(' ', '')
# Look ahead for the bracketed text that signifies nested list
l_x = re.split(r',(?=[[A-Za-z0-9',]+])|(?<=]),', x[1:-1])
print(l_x)
# Flatten and split the non nested list items
l_x0 = [item for items in l_x for item in items.split(',') if not '[' in items]
# Convert the nested lists to lists
l_x1 = [
    i[1:-1].split(',') for i in l_x if '[' in i
]
# Add the two lists
l_x = l_x0 + l_x1

This last solution will work on any list stored as a string, nested or not.

2

You can do this

**

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>x = '[ "A","B","C" , " D"]'
print(eval(x))
</code>
<code>x = '[ "A","B","C" , " D"]' print(eval(x)) </code>
x = '[ "A","B","C" , " D"]'
print(eval(x))

**
best one is the accepted answer

Though this is not a safe way, the best answer is the accepted one.
wasn’t aware of the eval danger when answer was posted.

1

Assuming that all your inputs are lists and that the double quotes in the input actually don’t matter, this can be done with a simple regexp replace. It is a bit perl-y, but it works like a charm. Note also that the output is now a list of Unicode strings, you didn’t specify that you needed that, but it seems to make sense given Unicode input.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import re
x = u'[ "A","B","C" , " D"]'
junkers = re.compile('[[" ]]')
result = junkers.sub('', x).split(',')
print result
---> [u'A', u'B', u'C', u'D']
</code>
<code>import re x = u'[ "A","B","C" , " D"]' junkers = re.compile('[[" ]]') result = junkers.sub('', x).split(',') print result ---> [u'A', u'B', u'C', u'D'] </code>
import re
x = u'[ "A","B","C" , " D"]'
junkers = re.compile('[[" ]]')
result = junkers.sub('', x).split(',')
print result
--->  [u'A', u'B', u'C', u'D']

The junkers variable contains a compiled regexp (for speed) of all characters we don’t want, using ] as a character required some backslash trickery.
The re.sub replaces all these characters with nothing, and we split the resulting string at the commas.

Note that this also removes spaces from inside entries u'[“oh no”]’ —> [u’ohno’]. If this is not what you wanted, the regexp needs to be souped up a bit.

If you know that your lists only contain quoted strings, this pyparsing example will give you your list of stripped strings (even preserving the original Unicode-ness).

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> from pyparsing import *
>>> x =u'[ "A","B","C" , " D"]'
>>> LBR,RBR = map(Suppress,"[]")
>>> qs = quotedString.setParseAction(removeQuotes, lambda t: t[0].strip())
>>> qsList = LBR + delimitedList(qs) + RBR
>>> print qsList.parseString(x).asList()
[u'A', u'B', u'C', u'D']
</code>
<code>>>> from pyparsing import * >>> x =u'[ "A","B","C" , " D"]' >>> LBR,RBR = map(Suppress,"[]") >>> qs = quotedString.setParseAction(removeQuotes, lambda t: t[0].strip()) >>> qsList = LBR + delimitedList(qs) + RBR >>> print qsList.parseString(x).asList() [u'A', u'B', u'C', u'D'] </code>
>>> from pyparsing import *
>>> x =u'[ "A","B","C" , " D"]'
>>> LBR,RBR = map(Suppress,"[]")
>>> qs = quotedString.setParseAction(removeQuotes, lambda t: t[0].strip())
>>> qsList = LBR + delimitedList(qs) + RBR
>>> print qsList.parseString(x).asList()
[u'A', u'B', u'C', u'D']

If your lists can have more datatypes, or even contain lists within lists, then you will need a more complete grammar – like this one in the pyparsing examples directory, which will handle tuples, lists, ints, floats, and quoted strings.

0

You may run into such problem while dealing with scraped data stored as Pandas DataFrame.

This solution works like charm if the list of values is present as text.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def textToList(hashtags):
return hashtags.strip('[]').replace(''', '').replace(' ', '').split(',')
hashtags = "[ 'A','B','C' , ' D']"
hashtags = textToList(hashtags)
Output: ['A', 'B', 'C', 'D']
</code>
<code>def textToList(hashtags): return hashtags.strip('[]').replace(''', '').replace(' ', '').split(',') hashtags = "[ 'A','B','C' , ' D']" hashtags = textToList(hashtags) Output: ['A', 'B', 'C', 'D'] </code>
def textToList(hashtags):
    return hashtags.strip('[]').replace(''', '').replace(' ', '').split(',')

hashtags = "[ 'A','B','C' , ' D']"
hashtags = textToList(hashtags)

Output: ['A', 'B', 'C', 'D']

No external library required.

This usually happens when you load list stored as string to CSV

If you have your list stored in CSV in form like OP asked:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>x = '[ "A","B","C" , " D"]'
</code>
<code>x = '[ "A","B","C" , " D"]' </code>
x = '[ "A","B","C" , " D"]'

Here is how you can load it back to list:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import csv
with open('YourCSVFile.csv') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
rows = list(reader)
listItems = rows[0]
</code>
<code>import csv with open('YourCSVFile.csv') as csv_file: reader = csv.reader(csv_file, delimiter=',') rows = list(reader) listItems = rows[0] </code>
import csv
with open('YourCSVFile.csv') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    rows = list(reader)

listItems = rows[0]

listItems is now list

7

To further complete Ryan’s answer using JSON, one very convenient function to convert Unicode is in this answer.

Example with double or single quotes:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>print byteify(json.loads(u'[ "A","B","C" , " D"]')
>print byteify(json.loads(u"[ 'A','B','C' , ' D']".replace(''','"')))
['A', 'B', 'C', ' D']
['A', 'B', 'C', ' D']
</code>
<code>>print byteify(json.loads(u'[ "A","B","C" , " D"]') >print byteify(json.loads(u"[ 'A','B','C' , ' D']".replace(''','"'))) ['A', 'B', 'C', ' D'] ['A', 'B', 'C', ' D'] </code>
>print byteify(json.loads(u'[ "A","B","C" , " D"]')
>print byteify(json.loads(u"[ 'A','B','C' , ' D']".replace(''','"')))
['A', 'B', 'C', ' D']
['A', 'B', 'C', ' D']

1

json.loads() and json.dumps() from json package is the equivalent way of javascript JSON.parse() and JSON.stringify() so use json solution to keep life simpler

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import json
a = '[ "A","B","C" , " D"]'
print(json.loads(a)) #['A', 'B', 'C', ' D']
b = ['A', 'B', 'C', ' D']
print(json.dumps(b)) # '["A", "B", "C", " D"]'
</code>
<code>import json a = '[ "A","B","C" , " D"]' print(json.loads(a)) #['A', 'B', 'C', ' D'] b = ['A', 'B', 'C', ' D'] print(json.dumps(b)) # '["A", "B", "C", " D"]' </code>
import json
a = '[ "A","B","C" , " D"]'
print(json.loads(a)) #['A', 'B', 'C', ' D']
b = ['A', 'B', 'C', ' D']
print(json.dumps(b)) # '["A", "B", "C", " D"]'

I would like to provide a more intuitive patterning solution with regex.
The below function takes as input a stringified list containing arbitrary strings.

Stepwise explanation:
You remove all whitespacing,bracketing and value_separators (provided they are not part of the values you want to extract, else make the regex more complex). Then you split the cleaned string on single or double quotes and take the non-empty values (or odd indexed values, whatever the preference).

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def parse_strlist(sl):
import re
clean = re.sub("[[],s]","",sl)
splitted = re.split("['"]",clean)
values_only = [s for s in splitted if s != '']
return values_only
</code>
<code>def parse_strlist(sl): import re clean = re.sub("[[],s]","",sl) splitted = re.split("['"]",clean) values_only = [s for s in splitted if s != ''] return values_only </code>
def parse_strlist(sl):
import re
clean = re.sub("[[],s]","",sl)
splitted = re.split("['"]",clean)
values_only = [s for s in splitted if s != '']
return values_only

testsample: “[’21’,”foo” ‘6’, ‘0’, ” A”]”

So, following all the answers I decided to time the most common methods:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from time import time
import re
import json
my_str = str(list(range(19)))
print(my_str)
reps = 100000
start = time()
for i in range(0, reps):
re.findall("w+", my_str)
print("Regex method:t", (time() - start) / reps)
start = time()
for i in range(0, reps):
json.loads(my_str)
print("JSON method:t", (time() - start) / reps)
start = time()
for i in range(0, reps):
ast.literal_eval(my_str)
print("AST method:tt", (time() - start) / reps)
start = time()
for i in range(0, reps):
[n.strip() for n in my_str]
print("strip method:t", (time() - start) / reps)
regex method: 6.391477584838867e-07
json method: 2.535374164581299e-06
ast method: 2.4425282478332518e-05
strip method: 4.983267784118653e-06
</code>
<code>from time import time import re import json my_str = str(list(range(19))) print(my_str) reps = 100000 start = time() for i in range(0, reps): re.findall("w+", my_str) print("Regex method:t", (time() - start) / reps) start = time() for i in range(0, reps): json.loads(my_str) print("JSON method:t", (time() - start) / reps) start = time() for i in range(0, reps): ast.literal_eval(my_str) print("AST method:tt", (time() - start) / reps) start = time() for i in range(0, reps): [n.strip() for n in my_str] print("strip method:t", (time() - start) / reps) regex method: 6.391477584838867e-07 json method: 2.535374164581299e-06 ast method: 2.4425282478332518e-05 strip method: 4.983267784118653e-06 </code>
from time import time
import re
import json

my_str = str(list(range(19)))
print(my_str)

reps = 100000

start = time()
for i in range(0, reps):
    re.findall("w+", my_str)
print("Regex method:t", (time() - start) / reps)

start = time()
for i in range(0, reps):
    json.loads(my_str)
print("JSON method:t", (time() - start) / reps)

start = time()
for i in range(0, reps):
    ast.literal_eval(my_str)
print("AST method:tt", (time() - start) / reps)

start = time()
for i in range(0, reps):
    [n.strip() for n in my_str]
print("strip method:t", (time() - start) / reps)

    regex method:     6.391477584838867e-07
    json method:     2.535374164581299e-06
    ast method:         2.4425282478332518e-05
    strip method:     4.983267784118653e-06

So in the end regex wins!

You can save yourself the .strip() function by just slicing off the first and last characters from the string representation of the list (see the third line below):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>>>> mylist=[1,2,3,4,5,'baloney','alfalfa']
>>> strlist=str(mylist)
['1', ' 2', ' 3', ' 4', ' 5', " 'baloney'", " 'alfalfa'"]
>>> mylistfromstring=(strlist[1:-1].split(', '))
>>> mylistfromstring[3]
'4'
>>> for entry in mylistfromstring:
... print(entry)
... type(entry)
...
1
<class 'str'>
2
<class 'str'>
3
<class 'str'>
4
<class 'str'>
5
<class 'str'>
'baloney'
<class 'str'>
'alfalfa'
<class 'str'>
</code>
<code>>>> mylist=[1,2,3,4,5,'baloney','alfalfa'] >>> strlist=str(mylist) ['1', ' 2', ' 3', ' 4', ' 5', " 'baloney'", " 'alfalfa'"] >>> mylistfromstring=(strlist[1:-1].split(', ')) >>> mylistfromstring[3] '4' >>> for entry in mylistfromstring: ... print(entry) ... type(entry) ... 1 <class 'str'> 2 <class 'str'> 3 <class 'str'> 4 <class 'str'> 5 <class 'str'> 'baloney' <class 'str'> 'alfalfa' <class 'str'> </code>
>>> mylist=[1,2,3,4,5,'baloney','alfalfa']
>>> strlist=str(mylist)
['1', ' 2', ' 3', ' 4', ' 5', " 'baloney'", " 'alfalfa'"]
>>> mylistfromstring=(strlist[1:-1].split(', '))
>>> mylistfromstring[3]
'4'
>>> for entry in mylistfromstring:
...     print(entry)
...     type(entry)
...
1
<class 'str'>
2
<class 'str'>
3
<class 'str'>
4
<class 'str'>
5
<class 'str'>
'baloney'
<class 'str'>
'alfalfa'
<class 'str'>

And with pure Python – not importing any libraries:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[x for x in x.split('[')[1].split(']')[0].split('"')[1:-1] if x not in[',',' , ',', ']]
</code>
<code>[x for x in x.split('[')[1].split(']')[0].split('"')[1:-1] if x not in[',',' , ',', ']] </code>
[x for x in  x.split('[')[1].split(']')[0].split('"')[1:-1] if x not in[',',' , ',', ']]

This is another solution if you don’t want to import any library:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>x = '[ "A","B","C" , " D"]'
def toList(stringList):
stringList = stringList.split('[')[1]# removes "["
stringList = stringList.split(']')[0]# removes "]"
stringList = stringList.split(',')#gets objects in the list
return [text.strip()[1:-1] for text in stringList] #eliminate additional " or ' in the string.
toList(x)
</code>
<code>x = '[ "A","B","C" , " D"]' def toList(stringList): stringList = stringList.split('[')[1]# removes "[" stringList = stringList.split(']')[0]# removes "]" stringList = stringList.split(',')#gets objects in the list return [text.strip()[1:-1] for text in stringList] #eliminate additional " or ' in the string. toList(x) </code>
x = '[ "A","B","C" , " D"]'
def toList(stringList):
  stringList = stringList.split('[')[1]# removes "["
  stringList = stringList.split(']')[0]# removes "]"
  stringList = stringList.split(',')#gets objects in the list
  return [text.strip()[1:-1] for text in stringList] #eliminate additional " or ' in the string.
toList(x)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>['A', 'B', 'C', ' D']
</code>
<code>['A', 'B', 'C', ' D'] </code>
['A', 'B', 'C', ' D']

The caveat to this method is that it doesn’t work if you have comma inside your string for example if your input is

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>x = '[ "A","B,F","C" , " D"]'
</code>
<code>x = '[ "A","B,F","C" , " D"]' </code>
x = '[ "A","B,F","C" , " D"]'

your output will be

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>['A', '', '', 'C', ' D']
</code>
<code>['A', '', '', 'C', ' D'] </code>
['A', '', '', 'C', ' D']

which is not what you want.

This solution is simpler than some I read in the previous answers, but it requires to match all features of the list.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>x = '[ "A","B","C" , " D"]'
[i.strip() for i in x.split('"') if len(i.strip().strip(',').strip(']').strip('['))>0]
</code>
<code>x = '[ "A","B","C" , " D"]' [i.strip() for i in x.split('"') if len(i.strip().strip(',').strip(']').strip('['))>0] </code>
x = '[ "A","B","C" , " D"]'
[i.strip() for i in x.split('"') if len(i.strip().strip(',').strip(']').strip('['))>0]

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>['A', 'B', 'C', 'D']
</code>
<code>['A', 'B', 'C', 'D'] </code>
['A', 'B', 'C', 'D']

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật