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 –
2. Invalid characters in digits like
3. Newline or linefeed characters (
This happens when you read a
txt file in a Python variable and trying string to float operation on its data.
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
float symbol etc. Print out those values which are creating issue and sanitize them.
You can also use exception handling (
try: str="0.67,5" str_to_float=float(str) except ValueError, e: print "error", e