Converting a string to a tuple

Charles G Waldman cgw at fnal.gov
Mon Apr 12 18:14:15 EDT 1999


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




More information about the Python-list mailing list