简体   繁体   中英

When trying to convert to float to do math it gives me an error

This is the error that it gives me.

ValueError: could not convert string to float: ''

the string has the following value(copied from the pycharm console):

283,00 €

After this bit of code below

num = file_row[7].strip('€  /\n')
num= num.replace(",",".")

It has the following value:

283.00

When I try to convert this to a float value, with num = float(num) it gives me the error above. From what I read prior to posting this, according to the error, it doesn't see the string to convert, but I know I have values in the num string of the format xxx.xx where x = [0,9]

I print num to be sure I have something in it before and after like so:

 num= file_row[7]
 print(num)
 num = file_row[7].strip('€  /\n')
 num= num.replace(",",".")
 print(num)

The print output copied from the console:

283,00 €

283.00

This is what the stacktrace shows:

The print output copied from the console:

283,00 € 283.00

Figured it out. I am reading a csv. and I am putting everything from a row in the csv in a list called file_row. But I am ignoring the empty rows, by an earlier condition looking at another string if its populated or not. Some are not. For those rows, this throws the error. Thanks guys and gals. You have been fantastic

You should use type(num) to make sure that your num is currently a correct string. If it is a correct string, if you are having multiple numbers, make sure that all of them are numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM