-1

I have a string that need to be spliced based on ,

x = '1,0.5,3'
y = x.split(',')
print(y)

//Result
//['1','0.5','3']

I would like to split the string but get an array of numbers as return value.

expected return

[1,0.5,3]
Chris Maes
  • 30,644
  • 6
  • 98
  • 124
Martin Christopher
  • 329
  • 1
  • 6
  • 17
  • You may refer here: https://stackoverflow.com/questions/1906717/splitting-integer-in-python – Pranay May 06 '19 at 09:06

3 Answers3

5
x = '1,0.5,3'
l = [float(a) for a in x.split(',')]

Result:

[1,0.5,3]

Used float() since you have a floating point in there. You can use int() but that will do some rounding

rdas
  • 18,048
  • 6
  • 31
  • 42
1

If you really need them to be ints instead of floats, you can truncate them for example:

>>> [int(float(e).__trunc__()) for e in x.split(",")]
[1, 0, 3]
Netwave
  • 36,219
  • 6
  • 36
  • 71
0

You have to convert each item:

y = [float(y) for y in x.split(',')] // Result: [1.0, 0.5, 3.0]

Note: Using int(y) directly gave me this error due to the "0.5":

File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0.5'
Zwepp
  • 186
  • 7