我想写一个函数,它接受一个字符串,找到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")
//tbsp的类似代码
我相信这对你有用?你知道吗
编辑:
在(1)处,配方=“1/2茶匙盐”
在(2)处,配方变为[“1/2”,“盐”]
然后把所有的字符串加在一起
split方法根据给定的参数拆分字符串并返回一个字符串数组
这里有一个解决方案,应该涵盖大多数情况。你知道吗
(1):下面是用
'tbsp (30g)'
替换句子的'tbsp'
部分的例子。插入的字符串('tbsp (30g)'
)是字符串格式化的结果。你知道吗相关问题 更多 >
编程相关推荐