webnat0
webnat0

Reputation: 2716

How do I convert string version of an array into an actual array?

s = "[[A, B],[E,R], [E,G]]"

Is there a built-in way to convert this string into an array? (s[][])

Upvotes: 1

Views: 129

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

If A B E R G are not variables but just a string then you can use the following code:

tmp = ''
for c in s:
   if c.isalpha():
      t+="'%s'"%c
   else:
      t+=c
eval(t) # will give you [['A', 'B'], ['E', 'R'], ['E', 'G']]

OR:(very ugly i know but don't beat me too much - just experementing)

evel(''.join(map(lambda x: s[x[0]] if not s[x[0]].isalpha() else "'%s'" % s[x[0]], enumerate(map(lambda c: c.isalpha(), s)))))

Upvotes: 1

circus
circus

Reputation: 2600

If you can slightly modify the string, you could use the JSON module to convert the string into list.

>>> import json

>>> s = '[["A", "B"], ["E", "R"], ["E", "G"]]'
>>> array = json.loads(s)
>>> array
[[u'A', u'B'], [u'E', u'R'], [u'E', u'G']]

Upvotes: 0

gnur
gnur

Reputation: 4733

There is, but in your case it will assume A B E R G to be variables, is this the case?
If this is not the case you will need to do some extra formatting with the string.

This will work if the variables A B E R G are set:
s = eval(s)

If the letters need to be strings you will have to do some kind of regexp to replace all occurrences of chars with quoted chars.

Upvotes: 1

Related Questions