
Convert (Parse) a string to a float in Python
The float()
converts strings to floats in Python.
a = '3.1415'
b = float(a)
print(b) # 3.1415
print(type(b)) # <class 'float'>
Note that the type()
returns an object type. The type of a string is str and the type of a float is float. The float()
can parse a string starting with a dot like .123
.
a = '.1415'
b = float(a)
print(b) # 0.1415
print(type(b)) # <class 'float'>
The float()
also parses an "int" string to a float.
a = '123'
b = float(a)
print(b) # 123.0
print(type(b)) # <class 'float'>
Comments
Powered by Markdown