-1

For data storage purposes I am trying to recover lists of floats from a .txt file. From the string like:

a = '[1.3, 2.3, 4.5]'

I want to recover:

a = [1.3, 2.3, 4.5]

I was expecting a simple solution like list(a), but I cannot find anything like that.

Pieter
  • 11

5 Answers5

3

Use the ast module.

Ex

import ast
print(ast.literal_eval('[1.3, 2.3, 4.5]'))

Output:

[1.3, 2.3, 4.5]
Rakesh
  • 78,594
  • 17
  • 67
  • 103
2

You can also use a more manual way:

[eval(x) for x in '[1.3, 2.3, 4.5]'.strip("[").strip("]").split(",")]
Out[64]: [1.3, 2.3, 4.5]
Mathieu
  • 5,044
  • 5
  • 25
  • 50
2

You could use json

import json
a = '[1.3, 2.3, 4.5]'
json.loads(a)
Adson Leal
  • 31
  • 3
0

well if you are sure that your input data is of type, a = '[1.3, 2.3, 4.5]' then you could use the eval command and assign it to same or a different variable.

a = '[1.3, 2.3, 4.5]'
b=eval(a)
print(b.__class__)  # to know if b is of type list or not
Surya Tej
  • 1,132
  • 1
  • 11
  • 21
0
a = a.split(",")
a[0] = a[0][1:]
a[-1] = a[-1][:-1]
a = [float(i) for i in a]

This should work :)

Tanay Agrawal
  • 362
  • 1
  • 9