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

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

1
  • 4
    By "array", do you mean Python list? Are the values supposed to be strings? Commented Jun 8, 2011 at 10:33

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If the letters were meant to be strings, there is no reason not to use the much safer ast.literal_eval instead of eval, which may execute arbitrary code if s has been tampered with.
1

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)))))

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.