Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,181 questions

56,073 answers

573 users

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 7 hours ago by avibootz

Related questions

...