I have a list [' 2.5', ' -1.7 5.1', ' 0.0 -0.1 3.6']. I would like to be able to get the value -1.7 for instance, but if I split the string with the separator '.', I only get nonsense (as it should). Do you have any suggestions?
CodePudding user response:
split by space ! for example :
l = [' 2.5', ' -1.7 5.1', ' 0.0 -0.1 3.6']
print(l[1].split(' ')[0])
output:
-1.7
CodePudding user response:
You need to strip
and split
each element i
in the list and then cast each of the resulting elements to float
, i.e.,
values = [' 2.5', ' -1.7 5.1', ' 0.0 -0.1 3.6']
float_values = []
for i in values:
for j in i.strip().split():
float_values.append(float(j))
# [2.5, -1.7, 5.1, 0.0, -0.1, 3.6]
print(float_values)
or as a list comprehension:
float_values = [float(j) for i in values for j in i.strip().split()]