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

0

3 Answers 3

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]
Sign up to request clarification or add additional context in comments.

5 Comments

Really nice dude, can you explain to me how it works?
much love to you man
You are welcome :)
I cant, I have to wait 15mins (1 left) but I will
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]

1 Comment

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).
-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

3 Comments

@soon Only if you do not know what you are doing. ;)
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.