Python raises “could not convert string to float” error when you try to convert a string that cannot be parsed as a floating-point number.
Empty String Conversion
If you try to convert an empty string to float, you will get the “could not convert string to float” error.
print(float(''))
Output
ValueError: could not convert string to float: ''
Converting a numerical string
If you try to convert a numerical string to float, you will face this error.
print(float('2.73%'))
Output
ValueError: could not convert string to float: '2.73%'
General string Conversion
If you try to convert a general string to a floating data type, you will get this error.
print(float('1.921KB'))
Output
ValueError: could not convert string to float: '1.921KB'
How to fix could not convert string to float error
There are the following ways to fix the errors.
- Using the re.findall() method to remove all characters and symbols.
- Use the str.strip() function to remove leading and trailing unwanted characters.
- Replace the unnecessary character(s) with an empty string.
- Handle the exception with a try-except block.
- Validate user input.
Using the re.findall() method
The re.findall() method from Python’s re (regular expressions) module can extract numbers, including floating-point numbers, from a string.
import re
input_string = 'k21.19b'
mid = re.findall(r'\d+\.\d+', input_string)
float_num = float(mid[0])
print(float_num)
Output
21.19
You can see that before converting it to a floating-point number, we extracted the floating-point number from a string and then converted it to float using the float() function.
Use the str.strip() method to remove extra whitespace
We can use the str.strip() function, which strips off(clears the matched regex).
input_string = '2.7365%'
float_num = float(input_string.strip('.%'))
print(float_num)
Output
2.7365
Using the str.replace() method to replace unnecessary characters
You can remove unnecessary characters and replace them with an empty string using the str.replace() method.
input_string = '2.7365%'
mid = input_string.replace("%", '')
float_num = float(mid)
print(float_num)
Output
2.7365
Handle the exception with a try-except block
If you’re not sure whether the input string is formatted correctly, use a try-except block to catch the ValueError exception that occurs when the conversion fails.
input_string = '2.7365%'
try:
float_value = float(input_string)
except ValueError:
print(f"Could not convert '{input_string}' to a float")
Output
Could not convert '2.7365%' to a float
Now, you can either prompt the user for a new input, set a default value, or handle the error in another appropriate way.
Validate user input (optional)
If you are receiving input from a user, you can use a function to validate and convert the input string to a float and then loop until a valid float is provided.
def get_float_from_user(prompt):
while True:
input_str = input(prompt)
input_str = input_str.strip()
try:
float_value = float(input_str)
return float_value
except ValueError:
print(f"Invalid input. Please enter a valid floating-point number.")
float_value = get_float_from_user("Enter a float: ")
Output
Enter a float: 19.21kb
Invalid input. Please enter a valid floating-point number.
Enter a float: 11
That’s it.