valueerror could not convert string to float – Code Example

Total
0
Shares

In this article we will provide you some code examples to resolve valueerror could not convert string to float. According to the error, you must be trying to convert some string value to float and it failed with this error. Not all string values can be converted to float. Sometimes we overlook strings like empty spaces or new line or line feed etc.

Code Example –

Error Code – Let’s see the common situations when Python throws valueerror could not convert string to float.

1. Having space in between number digits –

print(float("12.0 3"))

2. Invalid characters in digits like ,

print(float("12,037"))

3. Newline or linefeed characters (\r\n)

This happens when you read a csv or txt file in a Python variable and trying string to float operation on its data.

Solution

There is only one solution to this problem. You need to sanitize your input data for spaces, invalid characters, linefeed etc. Check for only valid characters like numbers, ., exponent, float symbol etc. Print out those values which are creating issue and sanitize them.

You can also use exception handling (try...except).

try:
    str="0.67,5"
    str_to_float=float(str)
except ValueError, e:
    print "error", e