Extract Number from String or Return Second Argument

  • Share this:

Code introduction


The function accepts two arguments, a string and a number, and extracts a number from the string. If the string does not contain any number, it returns the second argument.


Technology Stack : Behave, Regular Expressions, Python String Manipulation

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
from behave import given, when, then
import random
import re

def extract_number(text):
    numbers = re.findall(r'\d+', text)
    return int(numbers[0]) if numbers else None

def xxx(arg1, arg2):
    """
    This function takes two arguments, a string and a number, and extracts a number from the string.
    If the string does not contain any number, it returns the second argument.
    """
    # Extracting a number from the string using regular expression
    extracted_number = extract_number(arg1)
    
    # If the string does not contain a number, use the number provided as the second argument
    if extracted_number is None:
        return arg2
    
    # If a number was extracted, perform some operations with it
    return arg1 + " has the number " + str(extracted_number)