Reputation: 1109
Similar to Convert string representation of list to list but consider the elements in the list are not encased in quotes, e.g
x = '[a, b, c, ab, adc, defg]'
How could you convert this to a list of string elements in python?
['a', 'b', 'c', 'ab', 'adc', 'defg']
Upvotes: 1
Views: 69
Reputation: 1693
You could do following:
import re
x = '[a, b, c, ab, adc, defg]'
x = re.sub(r"[\[\]]", "", x)
split_x = x.split(',')
print(split_x)
Upvotes: 0
Reputation: 23815
Below
x = '[a, b, c, ab, adc, defg]'
l = x[x.find('[') + 1: x.find(']')].split(',')
print(l)
Upvotes: 0
Reputation: 11942
This should do the trick:
>>> x = '[a, b, c, ab, adc, defg]'
>>> [i.strip(',[]') for i in x.split()]
['a', 'b', 'c', 'ab', 'adc', 'defg']
But of course, this assumes this exact format and nothing else more complicated
Upvotes: 0
Reputation: 1167
As it's a string, you can take the square brackets off and split by your delimiter:
>>> x = '[a, b, c, ab, adc, defg]'
>>> x[1:-1].split(', ')
['a', 'b', 'c', 'ab', 'adc', 'defg']
Upvotes: 4