Libraries and Modules in Python

Solutions

In [35]:
def string_to_weight(weight):
    """Parse the passed string as a weight. Valid formats are 'X kg', 'X kilos', 'X kilograms' etc.""" 
    m = re.search("^\s*(\d+\.?\d*)\s*(kgs?|kilos?|kilograms?)\s*$", weight, re.IGNORECASE)
    if m:
        return float(m.groups()[0])
    else:
        raise TypeError("Cannot extract a valid weight from '%s'" % weight)
In [36]:
string_to_weight("23.5 kilos"), string_to_weight("5kg"), string_to_weight("10 kilogram")
Out[36]:
(23.5, 5.0, 10.0)

2

In [37]:
def get_number_and_unit(s):
    """Interpret the passed string 's' as "X units", where "X" is a number and
       "unit" is the unit. Returns the number and (lowercased) unit
    """
    m = re.search("^\s*(\d+\.?\d*)\s*(\w+)\s*$", s, re.IGNORECASE)
    if m:
        number = float(m.groups()[0])
        unit = m.groups()[1].lower()
        return (number, unit)
    else:
        raise TypeError("Cannot extract a valid 'number unit' from '%s'" % s)       
In [38]:
def string_to_height(height):
    """Parse the passed string as a height. Valid formats are 'X m', 'X centimeters' etc.""" 
    (number, unit) = get_number_and_unit(height)
    if re.search("cm|centimeters?", unit):
        return number / 100.0
    elif re.search("m|meters?", unit):
        return number
    else:
        raise TypeError("Cannot convert a number with units '%s' to a valid height" % unit)
In [39]:
def string_to_weight(weight):
    """Parse the passed string as a weight. Valid formats are 'X kg', 'X grams' etc.""" 
    (number, unit) = get_number_and_unit(weight)
    if re.search("kgs?|kilos?|kilograms?", unit):
        return number
    elif re.search("g|grams?", unit):
        return number / 1000.0
    else:
        raise TypeError("Cannot convert a number with units '%s' to a valid weight" % unit)
In [40]:
string_to_height("55 cm"), string_to_height("2m"), string_to_height("15meters")
Out[40]:
(0.55, 2.0, 15.0)
In [41]:
string_to_weight("15g"), string_to_weight("5 kilograms"), string_to_weight("5gram")
Out[41]:
(0.015, 5.0, 0.005)