Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to convert string to float in Python

Introduction

In this blog post, we will be exploring the process of converting a string to a float in Python. This is a common task that you might come across while working with data manipulation or when receiving user inputs that need to be converted to a numerical format for further processing.

Before we dive into the topic, let's understand some basic terminologies that we will be using in this post.

  • String: A string is a sequence of characters enclosed in single or double quotes. For example, "Hello, World!" or '123.45' are both strings in Python.
  • Float: A float (short for floating-point number) is a number with a decimal point. For example, 123.45 or -0.123 are both float numbers in Python.

Now that we have a basic understanding of strings and floats, let's jump into the process of converting a string to a float in Python.

Converting a String to a Float Using the float() Function

Python provides a built-in function called float() that can be used to convert a string to a float. The float() function takes a single argument, which is the string that you want to convert, and returns the float representation of the provided string.

Here's an example of how to use the float() function to convert a string to a float:

string_number = "123.45"
float_number = float(string_number)
print(float_number)

Output:

123.45

In this example, we have a string called string_number which contains the value "123.45". We then use the float() function to convert this string to a float and store the result in a variable called float_number. Finally, we print the value of float_number, which is the float representation of the provided string.

It is important to note that the float() function can only convert strings that represent valid float numbers. If you try to convert a string that does not represent a valid float number, you will get a ValueError. For example:

invalid_string = "Hello, World!"
float_number = float(invalid_string)

Output:

ValueError: could not convert string to float: 'Hello, World!'

In this example, we tried to convert the string "Hello, World!" to a float, which is not a valid float representation. As a result, Python raises a ValueError.

To prevent this error, you can use exception handling to catch the ValueError and take appropriate action. We will discuss this in more detail later in this blog post.

Handling Strings with Leading or Trailing Whitespaces

Sometimes, the strings that you want to convert to floats might contain leading or trailing whitespaces. The float() function can handle such strings without any issues. Here's an example:

string_number = "   123.45  "
float_number = float(string_number)
print(float_number)

Output:

123.45

In this example, the string string_number contains leading and trailing whitespaces. When we pass this string to the float() function, it automatically ignores the whitespaces and converts the string to a float.

Converting a String with a Thousands Separator

In some cases, you might come across strings that use a thousands separator, such as a comma (,), to make the numbers more readable. The float() function does not support converting strings with thousands separators directly. To convert such strings to floats, you can use the replace() method to remove the thousands separator before passing the string to the float() function.

Here's an example:

string_number = "1,234.56"
string_number_no_commas = string_number.replace(",", "")
float_number = float(string_number_no_commas)
print(float_number)

Output:

1234.56

In this example, we first remove the thousands separator (comma) from the string_number using the replace() method and store the result in a variable called string_number_no_commas. We then pass this new string to the float() function to convert it to a float.

Handling Errors While Converting Strings to Floats

As we mentioned earlier, you might encounter strings that cannot be converted to floats, which will cause a ValueError when using the float() function. To handle such cases gracefully, you can use exception handling with a try and except block.

Here's an example:

string_number = "Hello, World!"

try:
    float_number = float(string_number)
    print(float_number)
except ValueError:
    print(f"Cannot convert '{string_number}' to a float.")

Output:

Cannot convert 'Hello, World!' to a float.

In this example, we use a try and except block to handle the potential ValueError that might occur when converting the string_number to a float. If the conversion is successful, we print the float value. If a ValueError occurs, we print a custom error message indicating that the conversion failed.

Conclusion

In this blog post, we learned how to convert a string to a float in Python using the float() function. We also explored handling strings with leading or trailing whitespaces, converting strings with thousands separators, and using exception handling to deal with errors that might occur during the conversion process.

By understanding these concepts and techniques, you will be better equipped to handle various data manipulation tasks and user inputs that involve converting strings to floats in your Python programs.