How To Extract Floating Point From String Python

In this tutorial, we will learn how to extract floating-point numbers from a given text string in Python.

You may encounter scenarios where a text file or input string contains numeric data, and you need to extract and process these floating-point numbers. Python provides built-in string manipulation and regular expression libraries that enable us to perform this task with ease.

Step 1: Import Necessary Libraries

First, we need to import the necessary Python libraries, re for regular expressions.

Step 2: Define the Input String

Create a sample input string containing floating-point numbers and other text.

Step 3: Create the Regular Expression Pattern

Use a regular expression (regex) pattern to match floating-point numbers in the input string. The pattern to match floating numbers is:

This pattern matches the following components:
– Optional sign (+ or –) at the beginning
– Zero or more digits before the decimal point
– Decimal point
– One or more digits after the decimal point
– Optional sign followed by at least 1 digit

Step 4: Use the “findall” Function to Extract Matching Strings

Use the findall function from the re library to find and return all non-overlapping matches found in the input string according to the regex pattern.

Step 5: Convert Extracted Strings to Floats

The findall function returns a list of matching strings. We need to convert these strings into floating-point numbers using Python’sfloat function.

Step 6: Print the Extracted Floating-Point Numbers

Now that you have the extracted floating-point numbers, you can print them.

The output will display the list of extracted floating-point numbers:

[25.99, 12.49, 38.48]

Full Code

Here’s the full code for extracting floating-point numbers from a string:

Output

[25.99, 12.49, 38.48]

Conclusion

In this tutorial, we went over how to extract floating-point numbers from a given input string using Python’s built-in re library for regular expressions. This handy technique allows you to process numerical data embedded within text strings, paving the way for more advanced data processing and manipulation tasks.