Home > Mobile >  Python ValueError: could not convert string to float
Python ValueError: could not convert string to float

Time:12-10

line = 'f 1// 2// 3// 4//'
vertices = []
line = line.split(" ")
toks = line[1:]

for vertex in toks:
    l = vertex.split("/")
    #print(l)
    l = np.array[float(x) for x in l]).astype(_DT)
    position = (l[0])
    vertices.append(position)

print(vertices)
    

this is the output ['1', '2', '3', '3'] which is correct! but I am getting a "ValueError could not covert string to float: " at this line l = np.array[float(x) for x in l]).astype(_DT) but there are no leading or trailing whitespaces , not sure how to go about this error!!

when doing print(l) i get ['1', ''] ['2', ''] ['3', ''] ['4', '']

I tried using .strip() on line but that didn't do anything. Also tried replace(" ", "") didn't do anything either. I can't find where the actual problem is. How can I identify where there is white spaces? HOW do i remove the '' ?

CodePudding user response:

You can skip the empty strings in your array comprehension with if. You can use the fact that empty strings evaluate as false, and any nonempty string will evaluate as true:

[float(x) for x in l if x]
  • Related