在特定单词后插入字符串中的项

2024-06-02 13:49:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个函数,它接受一个字符串,找到tsp或tbsp格式,并将其转换为gram。你知道吗

然后,我将此信息存储在c中,并将其插入字符串中的tbsp/tsp字后面。因为字符串是不可变的,我想先把它转换成一个列表,但现在我有点卡住了。你知道吗

有人对怎么做有建议吗?:)

示例:

 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")

Tags: ofto函数字符串inconvertifrecipe
2条回答
if 'tsp' in recipe:                  (1)
    c = int(c) * 5
    recipe = recipe.split('tsp')     (2)
    recipe = recipe[0] + 'tsp (' + str(c) + 'g)' + recipe[1]

//tbsp的类似代码

我相信这对你有用?你知道吗

编辑:

在(1)处,配方=“1/2茶匙盐”

在(2)处,配方变为[“1/2”,“盐”]

然后把所有的字符串加在一起

split方法根据给定的参数拆分字符串并返回一个字符串数组

这里有一个解决方案,应该涵盖大多数情况。你知道吗

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):下面是用'tbsp (30g)'替换句子的'tbsp'部分的例子。插入的字符串('tbsp (30g)')是字符串格式化的结果。你知道吗

相关问题 更多 >