0

I have this string

'[334.0, 223.0, 41.0, 819.0]'

And I need to transform this in this array:

[334.0, 223.0, 41.0, 819.0]

Any ideas? Thanks

Rakesh
  • 81,458
  • 17
  • 76
  • 113
Miguel Santos
  • 1,806
  • 3
  • 17
  • 30

3 Answers3

3

Use the ast module.

Ex:

import ast
print(ast.literal_eval('[334.0, 223.0, 41.0, 819.0]'))

output:

[334.0, 223.0, 41.0, 819.0]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

Simple one-liner with no extra imports:

a = '[334.0, 223.0, 41.0, 819.0]'

b = [ float(i) for i in a[1:-1].split(',') ]

print b

Output:

[334.0, 223.0, 41.0, 819.0]
amitchone
  • 1,630
  • 3
  • 21
  • 45
  • `float(223)` will produce the output `223.0`. (It seems that the commenter deleted the comment. This was in response to: What if we have an integer value in `a`). – amitchone May 25 '18 at 10:54
-1

What about eval?

That would evaluate a string as if it is a python code.

For example:

string='[334.0, 223.0, 41.0, 819.0]'
a = eval(string)
print(a[0])

output:

334.0
Riccardo Petraglia
  • 1,943
  • 1
  • 13
  • 25
  • 4
    [Eval is evil](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – awesoon May 25 '18 at 10:46
  • @soon Only if you do not know what you are doing. ;) – Riccardo Petraglia May 25 '18 at 10:50
  • 2
    Let's be honest - most of developers do not know what are they doing. `ast.literal_eval` behaves like `eval` for objects and it is safe – awesoon May 25 '18 at 10:54