如何在python中创建循环字符串列表的函数

2024-09-30 22:19:01 发布

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

嗨,假设我有一个包含以下字符串值的列表:

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'

我怎样才能解决这个问题


Tags: and函数字符串列表参数foodresultprint
2条回答
food = ['apples', 'bananas', 'tofu', 'pork']

def concat(food):
    return ", ".join(food[:-1]) + " and " + food[-1]

print(concat(food))
## output 'apples, bananas, tofu and pork'

对于for循环,可以使用list的索引而不是list的内容来完成:

def formatList(food):
    result = ""
    for i in range(len(food)):
        if i == len(food)-1:
            result += f"and {food[i]}"
        else:
            result += f"{food[i]}, "
    return result

相关问题 更多 >