-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
  • 35,025
  • 12
  • 111
  • 136
Martin Christopher
  • 389
  • 1
  • 7
  • 21
  • 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
  • 20,604
  • 6
  • 33
  • 46
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
  • 40,134
  • 6
  • 50
  • 93
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