From: cgw at fnal.gov (Charles G Waldman)
Date: Mon, 12 Apr 1999 22:14:15 GMT
Subject: Converting a string to a tuple
In-Reply-To: <01be8530$65bb7120$52037e81@saints>
References: <01be8530$65bb7120$52037e81@saints>
Message-ID: <14098.28727.245158.616727@buffalo.fnal.gov>
X-UID: 129                                                  

Bruce Huzyk writes:
 > Here is a basic problem that is causing me much stress:
 > 
 > I have a string a = '(1, "abc\\def", 2)' that I would like to convert to a
 > tuple. 
 > 
 > I have tried eval(), but it interprets the backslashes.

The cheapest thing to do is this:

import string
def str_to_tup(s):
    return eval(string.replace(s, '\\', '\\\\'))

If you're concerned about safety (the "eval" could be evaluating any
Python code, possibly a hazard if the string is coming from user
input) then you don't want to use eval at all, you need to actually
process the string, looking for commas, quotes, backslashes, etc.  If
you need to do this, you may find some parser generator/lexical
analyzer tools already in existence, if you look around python.org




