[Tutor] Turning a string into a tuple? (Without eval?)

Kirby Urner urnerk@qwest.net
Fri, 28 Sep 2001 10:00:41 -0700


>
>It would be cool if it could handle nested lists, as our imaginary parse()
>does.  It's not a requirement, but it would be quite nice...
>
>I haven't written this program yet, but it sounds like it might be really
>useful for people who want to avoid the dangers of eval().  Does anyone
>want a crack at it first?  *grin*

Here's a first pass that handles only the very
restrictive case David shared in his example:
a quoted list of strings and integers needing to
be turned into a real list.

Danny proposed this be done sans eval (which useful
function I *don't* avoid like the plague):

  >>> def parse(input):
         """
         Converts quoted list of strings, integers to list
         sans any use of eval
         """
          terms = input.split(",")
          terms[0]  = terms[0][1:]
          terms[-1] = terms[-1][:-1]
          output = []
          for t in terms:
            try:
               nt = int(t)
               output.append(nt)
            except:
                if t.find("'")>-1:
                    t = t[t.find("'")+1:]
                    t = t[:t.find("'")]
                    output.append(t)
          return output

  >>> parse("['Alda', 11, 9, 6, 'Trey', 10, 12]")
  ['Alda', 11, 9, 6, 'Trey', 10, 12]

Kirby