2

I want to write a function that takes a string, finds the tsp or tbsp format, and converts that to gram.

Then, I store this information in c and have to insert it behind the tbsp/tsp word in the string. Since strings are immutable I was thinking of converting it to a list first, but now I am a bit stuck.

Anyone has advice on how to do this? :)

Examples:

 input                   output

"2 tbsp of butter" --> "2 tbsp (30g) of butter"

"1/2 tbsp of oregano" --> "1/2 tbsp (8g) of oregano"

"1/2 tsp of salt" --> "1/2 tbsp (3g) of salt"

def convert_recipe(recipe):

    c = ''

    for i in recipe: # save the digit
        if i.isdigit():
            c += i
    if 'tsp' in recipe: # convert tsp to gram
        c = int(c) * 5
    elif 'tbsp' in recipe: # convert tbsp to gram
        c = int(c) * 15

    # now we have c. Insert (c) behind tsp / tbsp in string    


recipe = recipe.split()
print(recipe)
convert_recipe("2 tbsp of butter")
3
  • if "1/2 tbsp" is once (8g), once (3g) and "2 tbsp" are (30g), something is seriously wrong with tbsp-math. Commented Apr 27, 2018 at 10:15
  • @Ev.Kounis "Given all the measures in tablespoon (tbsp) and in teaspoon (tsp), considering 1 tbsp = 15g and 1 tsp = 5g, append to the end of the measurement the biggest equivalent integer (rounding up)" Commented Apr 27, 2018 at 10:23
  • Could have added that to the question; it would have saved much time. Commented Apr 27, 2018 at 10:27

2 Answers 2

1

Here is a solution that should cover most cases.

from fractions import Fraction
from math import ceil

def convert_recipe(recipe): 
    weight = {'tbsp': 15, 'tsp': 5}  # store the weights for tsp and tbsp
    ts = 'tbsp' if 'tbsp' in recipe else 'tsp'
    temp = recipe.split()            # convert string to list
    quantity = float(Fraction(temp[temp.index(ts)-1]))
    new_recipe = recipe.replace(ts, '{} ({}g)'.format(ts, ceil(quantity*weight[ts])))  # see (1)
    return new_recipe


print(convert_recipe("2 tbsp of butter"))   # -> 2 tbsp (30g) of butter
print(convert_recipe("1/2 tbsp of butter")) # -> 1/2 tbsp (8g) of butter
print(convert_recipe("1/2 tsp of salt"))    # -> 1/2 tsp (3g) of salt

(1): here are are actually replacing the 'tbsp' part of the sentence with 'tbsp (30g)' for example. The string that is inserted ('tbsp (30g)') is a result of string formating.

Sign up to request clarification or add additional context in comments.

4 Comments

Nice, thank you. Could you ellaborate on this part --> recipe.replace(ts, '{} ({}g)'.format(ts, ceil(quantity*weigt[ts]))) or a resource where I could read about it?
Oh and this part as well : float(Fraction(temp[temp.index(ts)-1]))
I don't know why but this sentence does not return the right answer. "Add to the mixing bowl and coat well with 1 tbsp of olive oil & 1/2 tbsp of dried dill"), -- should be "Add to the mixing bowl and coat well with 1 tbsp (15g) of olive oil & 1/2 tbsp (8g) of dried dill"
@Daphne because multiple instances are not supported. The quantity is defined by the first occurrence. The examples provided in the question and the question body did not hint towards such a use case.
0
if 'tsp' in recipe:                  (1)
    c = int(c) * 5
    recipe = recipe.split('tsp')     (2)
    recipe = recipe[0] + 'tsp (' + str(c) + 'g)' + recipe[1]

// similar code for tbsp

I believe this will work for you?

Edit:

at (1), recipe = "1/2 tsp of salt"

at (2), recipe becomes ["1/2 ", " of salt"]

And then its all about adding the strings back together

The split method splits the string based on the given argument and returns an array of strings

5 Comments

It works! thank you. Could you describe what happens when you do recipe.split('tsp') ?
how does this deal with Fractions?
I haven't changed the logic behind calculating c.
@NannanAV There was no logic behind the calculation of c (c = '')
I didn't get what you meant by "How does this deal with Fractions?"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.