How to extract all floating-point numbers from a string of words in Python

1 Answer

0 votes
import re
from typing import List

# Pre-compile the regex pattern for optimal performance when scanning strings.
# \b creates word boundaries; \d+\.\d+ ensures numbers explicitly contain a decimal point.
FLOAT_PATTERN: re.Pattern = re.compile(r"\b\d+\.\d+\b")


def extract_floats(text: str) -> List[float]:
    """Extracts all floating-point numbers containing explicit decimal points

    from an input string.

    Args:
        text: Source string containing mixed text and numbers.

    Returns:
        List of extracted values as float primitives.
    """
    if not text:
        return []

    # re.finditer yields match objects lazily, preventing large temporary list allocations
    # float() converts string representations to standard double-precision floats
    return [float(match.group()) for match in FLOAT_PATTERN.finditer(text)]


def main() -> None:
    # Example input string
    s: str = "c/c++ c# go 893725.1045 java python 3.14 php 0.0076 javascript"

    # Extract floating-point numbers
    numbers: List[float] = extract_floats(s)

    # Display results
    print("Extracted floating-point numbers:")
    for num in numbers:
        print(num)


if __name__ == "__main__":
    main()



"""
run:

Extracted floating-point numbers:
893725.1045
3.14
0.0076

"""

 



answered Sep 17 by avibootz

Related questions

...