Last modified: Feb 08, 2026 By Alexander Williams

Python Convert String to Float | Easy Guide

Working with numbers is a core part of programming. Often, numeric data arrives as text. You need to convert it for calculations. Python makes this simple.

This guide explains how to convert a string to a float in Python. You will learn the main method, handle errors, and deal with special cases.

Why Convert String to Float?

Data from files, user input, or web APIs is often text. You cannot do math on text. You must convert it to a numeric type first.

A float represents a real number. It can have a decimal point. Converting a string to a float lets you perform arithmetic operations.

This is a fundamental skill for data processing, scientific computing, and financial applications.

The Primary Tool: The float() Function

The built-in float() function is your main tool. It takes a string argument and returns a floating-point number.

It is straightforward for well-formatted numeric strings.


# Basic conversion using float()
number_string = "3.14159"
pi = float(number_string)
print(pi)
print(type(pi))
    

3.14159
<class 'float'>
    

The float() function successfully converted "3.14159". The type() check confirms it's now a float.

It also works with integers in string form and scientific notation.


# Converting integer strings and scientific notation
int_string = "42"
sci_string = "1.23e-4"

float_from_int = float(int_string)
float_from_sci = float(sci_string)

print(float_from_int)   # Output: 42.0
print(float_from_sci)   # Output: 0.000123
    

Handling Conversion Errors

What if the string is not a valid number? The float() function will raise a ValueError.

This is a common error for beginners. You must handle it to make your program robust.


# This will cause a ValueError
invalid_string = "Hello World"
try:
    num = float(invalid_string)
except ValueError:
    print(f"Could not convert '{invalid_string}' to a float.")
    

Could not convert 'Hello World' to a float.
    

Using a try-except block is the best practice. It prevents your program from crashing.

You can also check if a string can be converted first. Use a custom function or a simple check.

Dealing with Commas and Extra Characters

Real-world data is messy. Numbers may have commas, currency symbols, or extra spaces. float() cannot handle these directly.

You must clean the string first. Use the str.replace() method to remove unwanted characters.


# Cleaning a string before conversion
price_string = "$1,250.75"
# Remove dollar sign and comma
clean_string = price_string.replace("$", "").replace(",", "")
price_float = float(clean_string)
print(price_float)  # Output: 1250.75
    

For more complex cleaning, you might use regular expressions. This is useful when data formats are inconsistent.

Remember, converting other data types is also crucial. For instance, you often need a Python Convert Number to String for display or logging.

Special Float Values

Python's float can represent special values. These include infinity and "Not a Number" (NaN).

The float() function can convert strings representing these concepts.


# Converting to special float values
inf_pos = float("inf")
inf_neg = float("-inf")
nan_val = float("nan")

print(inf_pos)  # Output: inf
print(inf_neg)  # Output: -inf
print(nan_val)  # Output: nan
    

These are useful in scientific computations. Handle them with care in comparisons.

Practical Example: Reading Numeric Data

Let's see a practical example. Imagine reading numbers from a text file or user input.

You must convert each string line to a float for processing.


# Simulating data from a file or input
data_strings = ["12.5", "  -3.8  ", "abc", "4.2e2", "1,000.5"]

converted_data = []
for item in data_strings:
    try:
        # Strip whitespace and remove commas
        clean_item = item.strip().replace(",", "")
        num = float(clean_item)
        converted_data.append(num)
    except ValueError:
        print(f"Skipping invalid value: '{item}'")

print("Converted list:", converted_data)
    

Skipping invalid value: 'abc'
Converted list: [12.5, -3.8, 420.0, 1000.5]
    

This pattern is very common. Clean, try to convert, and handle errors gracefully.

Conversion tasks are everywhere in Python. Just as you convert strings to floats, you might need to Python convert Sass to Css for web projects or Python Convert Images Between File Formats for graphics work.

Conclusion

Converting a string to a float in Python is essential. The float() function is the key tool.

Always use try-except blocks to handle invalid data. Clean your strings of commas and symbols first.

Mastering this conversion will make you better at handling real-world data. It is a foundational skill for any Python programmer.

Practice with different string formats. Build robust data processing pipelines with these techniques.