Reputation: 11
In python, I currently have the following:
s = '(num1, num2)'
I am wondering how I could convert this to a list with float values so that the format is as follows:
s = [ num1, num2 ]
What are possible ways to do this, preferably without having to import anything. Thank you in advance!
Upvotes: 1
Views: 56
Reputation: 1586
You can also try the built-in-function in python eval()
:
eval('(1e19, -23.430)')
or use regex
:
import re
s_in = '(1e19, -23.430)'
s_out = [float(s) for s in re.findall(r"\d+[e]\d+|[-+]\d+\.\d+|\d+", s_in)]
print(s_out)
output:
[1e+19, -23.43]
Upvotes: 0
Reputation: 900
This should work:
in_string = '(100, 200)'.replace('(', '').replace(')', '')
out = list(map(float, in_string.split(',')))
Take initial string input and use .replace to replace ( and ) with nothing. Then, make an output list consisting of a map that makes each element of input.split(',') (which is a list of elements separated by comma) and converts it to float.
Upvotes: 0
Reputation: 120429
Use ast.literal_eval
:
import ast
s = '(1e19, -23.430)'
>>> ast.literal_eval(s)
(1e+19, -23.43)
Upvotes: 1