Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - String

Extract numbers from a string - Python Program

Example 1 :

import re text = "Order 66 was executed in 2021" numbers = re.findall(r"\d+", text) print(numbers)

Output

 
OUTPUT  :
['66', '2021']
 

Example 2 :

import re def extract_numbers(input_string): """ Extracts all integer and floating-point numbers from a given string. Args: input_string: The string from which to extract numbers. Returns: A list containing all extracted numbers (as strings). """ # Regular expression to match integers and floating-point numbers # \d+ matches one or more digits # (\.\d+)? matches an optional decimal part (e.g., .99) # [eE][-+]?\d+ matches optional scientific notation (e.g., e-2, E+3) pattern = r'[-+]?\d+(\.\d+)?([eE][-+]?\d+)?' numbers = re.findall(pattern, input_string) # Join the matched groups to form complete numbers extracted_numbers = [] for num_tuple in numbers: extracted_numbers.append("".join(num_tuple)) return extracted_numbers # Example Usage my_string = "The price is $29.99, and the quantity is 10. Also, consider 5e-2 for calculation." extracted_list = extract_numbers(my_string) print(f"Original string: {my_string}") print(f"Extracted numbers: {extracted_list}")

Output

 
OUTPUT  :
Original string: The price is $29.99, and the quantity is 10. Also, consider 5e-2 for calculation.
Extracted numbers: ['29.99', '10', '5e-2']