1

I have a string formatted as a list of lists in a file. How can I get this into a variable in Python as a list?

E.g. data-string.txt

with open('data-string.txt') as f:
    str = f.read()

and

str = "[[1, 2, 3], [2, 3, 4], [3, 4, 5]]"

are equivalent. How can I get this into a real Python list? I have looked into splitting using multiple delimiters, but if that's the right way I haven't been able to set it up correctly.

M. Thompson
  • 95
  • 11

3 Answers3

3

You may use ast.literal_eval() to do your bidding:

import ast
s = ast.literal_eval("[1,2,3]")
s == [1,2,3]
Bharel
  • 23,672
  • 5
  • 40
  • 80
1

You can use json for some cases, but @Bharel answer is better at all

import json

with open('data-string.txt') as f:
    lst = json.load(f)
    print(lst)  # [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
sanyassh
  • 8,100
  • 13
  • 36
  • 70
-1

How about this:

// convert original string to type list
str1 = list("[[1, 2, 3], [2, 3, 4], [3, 4, 5]]")

// create a new string using the following, which converts same to a 3 x 3 list
str2 = ''.join(str(e) for e in str1)

// prints out as [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

// https://stackoverflow.com/questions/5618878/how-to-convert-list-to-string
Mike
  • 201
  • 2
  • 14