-1

I have a string in the following format:

s = "['1', '2', '['a', 'b']']"

And I want to convert it to this list, where each element is not a string:

l = [1, 2, ['a', 'b']]

How can I do that if I don't know from the beginning how long each of the final elements of the list will be?

martineau
  • 119,623
  • 25
  • 170
  • 301
Nadni
  • 178
  • 1
  • 3
  • 17
  • May I ask why you would want to do this?(And by the way, don't use builtin names such as `str` or `list` for variable names. Its bad practice) – Christian Dean Oct 04 '16 at 10:59
  • 6
    at least post a well formed string – e4c5 Oct 04 '16 at 11:00
  • That is not a proper string in the first place – Venu Saini Oct 04 '16 at 11:01
  • I have just corrected the string, thanks for pointing it out. I want to do that because the string is in an output file, and I need to load the informations on that file in another program. – Nadni Oct 04 '16 at 11:04
  • 1
    Where is the string coming from? Also are they really all single quotes and how deep in the nesting? – Padraic Cunningham Oct 04 '16 at 11:04
  • No, the quotes around the square brackets are double in the file, but when I first typed them as they are I received those comments about the string not being well formed – Nadni Oct 04 '16 at 11:12
  • What does the actual line in the file look like, and do you have any control over the file being produced ? – R.Sharp Oct 04 '16 at 11:13
  • No, I have no control over the file that gives me that string. The actual string is as follows: ['29/09/2016', "['Leo', 'Jeanette', 'Eddie']", "['Eddie', 'Leo', 'Jeanette']", '[20, 10, 5]', '\n'] – Nadni Oct 04 '16 at 11:15
  • @Efferalgan and the irony is that the question you linked to is also marked as a duplicate. Its a small world after... – Christian Dean Oct 04 '16 at 11:22
  • That's not entirely true, I guess. Here, some parts of the list should be converted to floats or integers, while others remain strings or even lists? – nostradamus Oct 04 '16 at 11:25
  • @Efferalgan No, I didn't mean you had to change it. Its fine. higher rep users usually sort out duplicates. – Christian Dean Oct 04 '16 at 11:30

1 Answers1

2

Convert small change in input then you will get get output very easily, like this,

In [1]: s = """['1', '2', "['a', 'b']"]"""
In [2]: print s
['1', '2', "['a', 'b']"]
In [3]: out = eval(s)
In [4]: out
Out[1]: ['1', '2', "['a', 'b']"]
In [5]: out[2] = eval(out[2])
In [6]: out
Out[2]: ['1', '2', ['a', 'b']]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52