To convert a string variable to a float in Python, use the float() function.

x = "1"
y = float(x)

print(y)

#Output:
1.0

When working with string variables in Python, the ability to easily be able to use and change these variables is valuable.

One such situation is if you want to create a float from a string variable.

To convert a string variable to a float in Python, use the float() function.

float() takes a string variable which represents a floating-point number, such as “12.2” or “4.9”, and returns a float variable.

Below shows a few simple examples of how you can use float() to convert a string to a float in Python.

a = "1"
b = "12.2"
c = "43.001"

print(float(a))
print(float(b))
print(float(c))

#Output:
1.0
12.2
43.001

Using float() to Convert String to Float in Python

To use float(), there are a few things you should know. First, you need to pass a string literal representing a floating-point number.

For example, if you try to pass a string which has letters, then you will get a ValueError.

If you pass a string representing an integer to float, you will get the floating-point representation of that integer. If you instead what to convert a string to an integer in Python, use int().

Below shows a few more examples of how to use float() and shows some common errors which might come from the use of float().

a = "1"
b = "1.23"
c = "abc"

print(float(a))
print(float(b))
print(float(c))

#Output:
1.0
1.23
ValueError: could not convert string to float: 'abc'

Hopefully this article has been useful for you to learn how to convert a string to float with Python.

Categorized in:

Python,

Last Update: March 12, 2024