Search code examples
pythonsplittuples

Splitting string in tuple


I have a tuple of string and I am trying to split the string so that when I search for the ingredient peanuts it will print out (300.0, 'g')

    recipe = ('peanut butter', '300 g peanuts,0.5 tsp salt,2 tsp oil')

What I want to achieve

    get_ingredient_amount('peanuts', recipe)
    prints  --> (300.0, 'g')

What I did

    def get_ingredient_amount(recipe):
        for idx, (x, y,z) in enumerate(recipe):
             recipe[idx] = (float(x), str(y), str(z))
             return recipe

**Erorr received ValueError: too many values to unpack **


Solution

  • You could try my function to get the value of the ingredient you want. Note that your format must be like in your example

    def get_ingredient_amount(ingredient_name, recipe):
        for item in recipe[1].split(','):
            if ingredient_name in item:
                amount, unit = item.split()[:2]
                return float(amount), unit
        return None
    
    
    recipe = ('peanut butter', '300 g peanuts,0.5 tsp salt,2 tsp oil')
    result_peanuts = get_ingredient_amount('peanuts', recipe)
    result_salt = get_ingredient_amount('salt', recipe)
    
    print(result_peanuts) #(300.0, 'g')
    print(result_salt) #(0.5, 'tsp')