5

I have referred to many sources but most use json.loads() or ast.literal_eval() which doesn't work for my case:

x = '[(0.0, 58.099669), 56565, Raining]'

Intended output:

x = [(0.0, 58.099669), 56565, 'Raining']

Is there any workaround for this?

Tonechas
  • 13,398
  • 16
  • 46
  • 80
Weiting Chen
  • 213
  • 2
  • 9
  • 1
    Should the `None` become the *string* `'None'`, or an actual `None` object? How will you be able to tell? – Karl Knechtel Dec 12 '20 at 01:51
  • @KarlKnechtel Thanks for pointing this out. I have since edited and removed the None as I don't think that should be the point of this question. The main objective here is to convert the string of a list without double quoted elements into a string. I believe I could deal with None from there on. – Weiting Chen Dec 12 '20 at 01:57
  • 3
    What created this text? We can offer de-facto solutions, but it might not fit the real problem. – tmrlvi Dec 12 '20 at 01:58
  • 3
    There is a broader point to this, though. The entire reason you're only finding tools that deal with data with quotes in it, is that *you need the quotes to avoid ambiguity*. – Karl Knechtel Dec 12 '20 at 01:58
  • 1
    You can always write a parser, but you can't write it until you know the variability of your input data. – Laggs Dec 12 '20 at 01:59
  • 1
    I see, thank you for the comments. I see the point of the double quotes now. This text is generated from a database representation of the underlying data. I doubt I have access to change the data structure from within. For this particular instance, the format is fixed: [(A, B), C, D ,E]' where A, B, C, D and E could only be alphanumeric. Yes, I have thought of a regex parser but I was thinking if there exists a more elegant solution. – Weiting Chen Dec 12 '20 at 02:03

1 Answers1

5

What about this:

class default_key(dict):
    def __missing__(self, key):
        return key

d = default_key()
x = '[(0.0, 58.099669), 56565, Raining]'

res = eval(x, d, {})
# res = [(0.0, 58.099669), 56565, 'Raining']

Explanation: eval normally uses the globals() and locals() dict. However if you don't provide locals() and replace globals() with a dict that returns the name of a key when a lookup is done (and the key isn't found), then every 'variable' name in the given list will be converted to a string when eval is called.

This could still be unsafe however. See this.

ssp
  • 1,666
  • 11
  • 15