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

Patrick K. O'Brien pobrien@orbtech.com
Fri, 28 Sep 2001 12:47:19 -0500


While I admire this effort, it seems to me that we could easily end up with
one heck of a complex program trying to avoid eval(). I suppose you could
look for '[' and ']' as the first and last characters of the input string as
a way to avoid eval()ing something that wouldn't result in a list. But I'm
not sure that would avoid all the potential evils of eval(). Makes for an
interesting problem, though, that's for sure.

---
Patrick K. O'Brien
Orbtech (http://www.orbtech.com)
"I am, therefore I think."

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Kirby Urner
Sent: Friday, September 28, 2001 12:01 PM
To: Danny Yoo
Cc: David L. Lerner; tutor@python.org
Subject: Re: [Tutor] Turning a string into a tuple? (Without eval?)


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


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor