[Solved] ValueError: could not convert string to float

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:

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:

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:

  1. When a numeric string contains a comma or other delimiters/special- characters.
  2. 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.

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:

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.

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:

💡 Solution 3: Using Regex

Another approach to solving our problem is to use the regex module and eliminate the special characters accordingly.

Example:

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.

Related Posts

  • Truncate float in Python
    02 November

    Truncate float in Python

    Table of ContentsHow to truncate float in Python?Using f-strings to truncate float in Python.Using the int() function to truncate float in Python.Using the str() function to truncate float in Python.Using the round() function to truncate float in Python. Truncating a floating-point number is a widely used practice and helps in making the calculations and results […]

  • Python for loop increment by 2
    01 November

    For Loop Increment By 2 in Python

    Table of ContentsPython For Loop Increment By 2 Using the range() FunctionPython For Loop Increment By 2 Using List SlicingConclusion We often use a for loop in python to iterate over a container object like a list or tuple. We also use for loops to perform tasks a fixed number of times. In python, the […]

  • Check if input is integer in Python
    01 November

    Check if input is integer in Python

    Table of ContentsUsing the isdigit() method to check if input is integer in Python.Using the isnumeric() method to check if input is integer in Python.Using exception handling along with the int() function to check if input is integer in Python.Using Regular Expression to check if input is integer in Python. There is wide use of […]

  • How to decrement for loop in Python
    28 October

    How to decrement for loop in python

    Table of ContentsWhat is for loop in Python?Ways to decrement the for loop in PythonUsing the start, stop and step parameters in range() functionUsing the reversed() functionUsing the while loopConclusion We use the for loop widely in the programming world. Most programs, whether highly complex or not, contain this loop. Sometimes, depending on the conditions, […]

  • Get random boolean in Python
    28 October

    Get random boolean in Python

    Table of ContentsWhat are Boolean Values?Ways to Generate Random Boolean in PythonUsing the random.getrandbits() functionUsing the random.choice() functionUsing the random.random() functionUsing the random.randint() functionUsing the numpy.random.choice() functionUsing the numpy.random.rand() functionUsing the numpy.random.randint() functionUsing the faker.pybool() functionConclusion What are Boolean Values? Python has a built-in data type Boolean that represents True and False values. It has […]

  • 25 October

    Increment operator in python

    Table of ContentsPython’s distinct way of using the increment operatorWays to increment a variable in PythonUsing the augmented assignment operatorUsing the step parameter in the range() functionThe role of immutability in Python The increment process is among the basic and the essentials of any programming language. We use it in problem-solving and when there is […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.