嗨,假设我有一个包含以下字符串值的列表:
food = ['apples', 'bananas', 'tofu', 'pork']
我的任务是编写一个函数,该函数将列表值作为参数,并返回一个字符串,其中所有项由逗号和空格分隔,最后一项前插入“and”
我的解决办法是:
def formatList(food):
result = ""
for idx in food:
result += idx + "," + " "
return result
如果我打印此调用函数,结果是:
print(formatList(food))
>> apples, bananas, tofu, pork,
预期输出应为:
print(formatList(food))
>> 'apples, bananas, tofu, and pork'
我怎样才能解决这个问题
对于for循环,可以使用list的索引而不是list的内容来完成:
相关问题 更多 >
编程相关推荐