Table of Contents
Overview
Problem Statement: How to fix valueerror: couldnot convert string to float
in Python?
🐞 What is “ValueError” in Python?
In Python, a value is the information that is stored within a specific object. When you encounter a ValueError
in Python, it means that there is a problem with the content of the object, you tried to assign the value to.
Example:
1 2 3 |
print(int('xy')) |
Output:
Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/rough.py”, line 1, in
print(int(‘xy’))
ValueError: invalid literal for int() with base 10: ‘xy’
Explanation: Python raises a ValueError
when a function’s argument is of an inappropriate type. Thus in the above example, when you tried to typecast a string value to an integer value, it leads to the occurrence of ValueError
.
➥ What does ValueError: could not convert string to float mean?
float()
is an inbuilt method in Python which returns a floating-point number from another numeric data-type( for example – int
) or a string
.
However, you can only use the float()
method on a string value that represents or looks like a floating-point value ( i.e. string values that represent numbers). This means that you cannot convert a normal string value like an alphabet to a floating-point value.
Example:
1 2 3 4 5 6 |
text = "Max" num = "25.65" print(float(num)) print(float(text)) |
Output:
25.65
Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/rough.py”, line 4, in
print(float(text))
ValueError: could not convert string to float: ‘Max’
Explanation: In the above example, num
which contains a numeric text value was successfully converted to a floating-point number, while an error occurred at line 4, when you tried to convert a string that represents a normal text, which is not supported by the float()
function in Python.
There are 2 major reasons that lead to ValueError: could not convert string to float
while you try to use the float()
method on a numeric string value. These are:
- When a numeric string contains a comma or other delimiters/special- characters.
- When a numeric string contains non-special characters.
Now that we know the reason behind the occurrence of this error, let’s dive into the solutions.
💡 Solution 1: Using map() + split() + float()
Sometimes, while working with data, we could be dealing with decimal numbers.
Note:
map()
is a built-in method in Python that allows you to transform the items in an iterable without the need of an explicit for loop.- The
split()
method splits a string into a list using a delimiter, separator.
Example: Let’s discuss how to resolve a problem in which we have a .
separated floating-point numbers and we need to convert them and store in a list containing float numbers.
1 2 3 4 5 6 |
ip = '192.168.10.0' print("String: ", ip) print("Extracted octets: ", float(ip)) |
Output:
String: 192.168.10.0
Traceback (most recent call last):
File “main.py”, line 3, in
print(“Extracted octets: “, float(ip))
ValueError: could not convert string to float: ‘192.168.10.0’
Solution:
1 2 3 4 5 6 7 8 9 |
ip = '192.168.10.0' print("String: ", ip) res = list(map(float,ip.split('.'))) print("Octets: ") for i in res: print(i) |
Output:
String: 192.168.10.0
Octets:
192.0
168.0
10.0
0.0
Explanation: In the above solution, we converted a string to a list containing float values by using split()
to separate the string and then convert the string to float using float()
. We have performed the task of mapping using the map()
method.
💡 Solution 2: Using replace() Method
replace()
is a built-in method in Python which replaces a specified phrase with another specified phrase.
Let’s have a look at this example to illustrate more about the problem and its solution.
1 2 3 4 5 6 |
dollar = '$100' rupees = 72.55 * float(dollar) print("{} = Rs.{}".format(dollar, rupees)) |
Output:
Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/rough.py”, line 2, in
Rupees = 72.55*float(dollar)
ValueError: could not convert string to float: ‘$100’
Explanation: In the above example, we two data types: an integer and a string. So, if you try to pass the numeric value (rupees
) to the float()
method, it will yield the expected output, but Python will raise a ValueError
if you try to pass the string value (dollar
) to the float()
method.
Solution: You can use replace()
method to convert or remove the $
character. Let’s have a look at the solution:
1 2 3 4 5 6 |
dollar = '$100' rupees = 72.55 * float(dollar.replace('$','')) print("{} = Rs.{}".format(dollar, rupees)) # Output: $100 = Rs.7255.0 |
💡 Solution 3: Using Regex
Another approach to solving our problem is to use the regex module and eliminate the special characters accordingly.
Example:
1 2 3 4 5 6 |
import re a = '$100' res = re.sub('[^0-9]+', '', a) print(float(res)) |
Output:
100.0
Conclusion
I hope this article helped you and answered your questions. Please stay tuned and subscribe for more exciting articles.
Read here: How to Fix TypeError: ‘int’ Object Is Not Subscriptable In Python?
This article was submitted by Shubham Sayon and co-authored by Prakritee Dev.