-2

I have a list of string like the following, and I want to convert it to the following; could you please help me with that;

Here is my list:

IN = ['7','8',"['#15140C', '#977E4F']"]

And here is the output that I want.

OUTput = [7,8,['#15140C', '#977E4F']]

I try to use [float(i) for I in range(Len(list))].

  • Here's a hint: `['#15140C', '#977E4F']` isn't a `float`, so your `OUTput =` line will fail. Also, there's no real need to try to do this in a single line. – fireshadow52 Mar 02 '23 at 04:42
  • Yes. I can convert the first part, but for the second part, I have a problem. – Jessica trevor Mar 02 '23 at 04:45
  • Does this answer your question? [How to convert string representation of list to a list](https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list) – Pranav Hosangadi Mar 02 '23 at 05:03
  • @PranavHosangadi this appears to be, instead, a list of string representations of other things. – Karl Knechtel Mar 02 '23 at 05:04
  • @Karl oops, I misread the first two strings as integers and thought op only needed to convert the third string to a list. The solution for the string representation of a list will also work for the string representation of an int, so that link should still be helpful! – Pranav Hosangadi Mar 02 '23 at 05:05
  • You can use eval on each item to build the output list : `OUTput = list(map(eval,IN))` – Alain T. Mar 02 '23 at 05:22
  • OP, were you helped by either of the answers provided? If so, please mark one as "accepted"! – ddejohn Mar 18 '23 at 04:59

2 Answers2

3

You can use ast.literal_eval to evaluate those strings as literals:

In [1]: from ast import literal_eval

In [2]: IN = ['7','8',"['#15140C', '#977E4F']"]

In [3]: [literal_eval(x) for x in IN]
Out[3]: [7, 8, ['#15140C', '#977E4F']]
ddejohn
  • 8,775
  • 3
  • 17
  • 30
1

@ddejohn's answer relies on input to be trusted, which is not always the case ^U.

As they corrected me, ast.literal_eval() is much safer than eval(), and hardly less safe than JSON parsing. Still, json.loads() turns out to be much faster!

So here's a JSON solution:

>>> import json
>>> IN = ['7','8',"['#15140C', '#977E4F']"]
>>> [json.loads(s.replace("'", '"')) for s in IN]
[7, 8, ['#15140C', '#977E4F']]

(Since JSON uses double quotes for strings, we have to replace single quotes before deserializing).

Nikolaj Š.
  • 1,457
  • 1
  • 10
  • 17
  • 1
    `ast.literal_eval()` only parses Python literals, which is perfectly safe -- you're thinking about `eval()` which executes arbitrary Python. – ddejohn Mar 02 '23 at 23:13
  • I know the difference between `eval` and `literal_eval`, and it might be a prejudice, but I'm always thrown off by anything `eval`-like. You are probably right, I'll amend my answer to be less dogmatic =) – Nikolaj Š. Mar 03 '23 at 08:35