How to convert Python strings to floats
Converting a Python string into a float can help you avoid errors that result from including non-numeric strings in arithmetic operations.
What kind of Python strings can be converted to floats?
If you want to convert a Python string to a float, the string needs to have a valid numerical representation as a floating-point value. This means that it can contain numbers in decimal format, which includes decimal points and scientific notation (such as "3.14"
or "2.7e-3"
). However, it can’t contain additional characters, spaces or characters that don’t represent numerical values. If it does, the conversion won’t work.
String–float conversion is a basic function and is included in every version of Python. However, there might be subtle differences in how some methods and functions work in different versions. Be sure to keep an eye out for errors that can arise during conversions. For example, entering a string that doesn’t represent a valid number will give rise to an error. And special values like NaN
(Not a Number) and Infinity
can’t be converted into floats. That means developers working with conversions need to be able to handle errors appropriately. Using try/except blocks to catch and react to errors is one way to do this.
How to convert Python strings with float()
The float()
function is a built-in Python method that converts strings to floats. It’s often used to change user input from strings to numeric formats so that the input can be used in calculations or numerical operations. In programs that work with various kinds of data, float()
is used to ensure that data remains consistent by converting values into a numerical format.
To convert Python strings to floats, use float()
and enter a valid string as the argument:
str1 = "3.1416"
float_value = float(str1)
print(float_value) # Output: 3.1416
pythonYou can also convert other numerical types like int
and complex
into a floating number by running them through float()
.
Try/except blocks can be used to catch invalid user input when converting strings to floats:
while True:
user_input = input("Enter a number: ")
try:
float_value = float(user_input)
print("Entered number as float:", float_value)
break # Exit the loop if the conversion was successful
except ValueError:
print("Invalid input! Please enter a numeric value.")
# The loop continues to prompt for valid input
pythonThe above code is a loop that prompts users to enter a number. It then attempts to convert that value into a floating number. In the try block, float(user_input)
is meant to convert the string entered by the user into a float. If the conversion was successful, the number is stored under float_value
and returned. The break
statement then terminates the loop and moves on with the program.
If a ValueError occurs when converting the string to a float, the code in the except block is executed. This can happen if the user enters a value that can’t be converted into a float, like a letter. In this case, a message says that the input is invalid and the loop requests valid input again.
How to convert Python strings to floats with NumPy
If you want to convert a Python string to a float with NumPy, you can use the function numpy.float64()
. It will give you a 64-bit floating number.
import numpy as np
string_value = "3.1416"
float_value = np.float64(string_value)
print(float_value) # Output: 3.1416
pythonFirst you’ll need to import NumPy in your script if it’s not already installed. You can then use NumPy to apply the function numpy.float64()
to the string string_value
to convert it into a 64-bit floating number.
How to use str()
If, on the other hand, you want to convert a float into a string, you can use the str()
function. This function converts other values into strings.
float_number = 3.1416
string_number = str(float_number)
print(string_number) # Output: "3.1416"
pythonIn the above example, the float value 3.1416
is converted into the string "3.1416"
using str()
.
str()
is also useful for concatenating several float values with f-strings (a Python string format).
float_value1 = 3.1416
float_value2 = 2.7182
float_value3 = 1.6180
string_concatenation = f"Concatenation of: {str(float_value1)}, {str(float_value2)}, and {str(float_value3)}"
print(string_concatenation) # Concatenation of: 3.1416, 2.7182, and 1.6180
pythonNote that when converting floats to strings with str()
, the resulting string will then be represented as text and will no longer be available for numerical calculations or mathematical operations. To use it in calculations, you’ll have to turn it back into a numerical form (like a float).
Read about other kinds of conversions in our Digital Guide. We explain how to convert Python strings to lists and Python strings to datetime objects.
- 99.9% uptime and super-fast loading
- Advanced security features
- Domain and email included