1

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']
ZeroStack
  • 1,049
  • 1
  • 13
  • 25

4 Answers4

4

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']
0

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

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
0

Below

x = '[a, b, c, ab, adc, defg]'
l = x[x.find('[') + 1: x.find(']')].split(',')
print(l)
balderman
  • 22,927
  • 7
  • 34
  • 52
0

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)
Masudur Rahman
  • 1,585
  • 8
  • 16