-2

I just ran into an unsolved Solution ;)

I want to get a String into a list of lists.

string = r'ABC:=[[0,0,110],[1,0,0,0],[1,0,0,0],[9e+09,9e+09,9e+09,9e+09,9e+09,9e+09]];'
new_string = string.strip().split('=')
# now new_string[1][:-1] does look like a list of lists but everything i tried i just got a string.

Maybe someone here got an idea how I can get it like

data = [[0,0,110],[1,0,0,0],[1,0,0,0],[9e+09,9e+09,9e+09,9e+09,9e+09,9e+09]]

Thanks

TimeO2
  • 1
  • 1
  • 1
    Possible duplicate of [How to convert comma-delimited string to list in Python?](https://stackoverflow.com/questions/7844118/how-to-convert-comma-delimited-string-to-list-in-python) – Chris Maes Sep 27 '19 at 13:50
  • 2
    Welcome to Stack Overflow. Please read this: https://stackoverflow.com/help/how-to-ask – averwhy Sep 27 '19 at 13:50
  • 1
    @ChrisMaes I don't think that duplicate directly answers OP's question. [This](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) might be a better pick – C.Nivs Sep 27 '19 at 14:12
  • @C.Nivs: I agree but cannot change my flag. – Chris Maes Sep 27 '19 at 14:20
  • Possible duplicate of [Convert string representation of list to list](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) – C.Nivs Sep 30 '19 at 16:12

2 Answers2

5

Use the ast library to transform the string into a data structure:

import ast

# string is a module in python, to avoid aliasing, use
# variable names that ideally don't shadow builtins
mystring = r'ABC:=[[0,0,110],[1,0,0,0],[1,0,0,0],[9e+09,9e+09,9e+09,9e+09,9e+09,9e+09]];'

# get everything to the right of the = sign, and you don't need the semicolon
mystring = mystring.strip().split('=')[-1].rstrip(';')

# returns a list
mylist = ast.literal_eval(mystring)

[[0, 0, 110], [1, 0, 0, 0], [1, 0, 0, 0], [9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0]]
C.Nivs
  • 9,223
  • 1
  • 14
  • 34
1

eval also works fine.

mystring = r'ABC:=[[0,0,110],[1,0,0,0],[1,0,0,0],[9e+09,9e+09,9e+09,9e+09,9e+09,9e+09]];'

mystring = mystring.strip().split('=')[-1].rstrip(';')

data = eval(mystring)
print(data)
# output: [[0, 0, 110], [1, 0, 0, 0], [1, 0, 0, 0], [9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0]]
王万鹏
  • 116
  • 1
  • 5