添加'和'在字符串列表中的最后一项之前

时间:2015-04-19 15:50:36

标签: python string list join

好的,所以我试图创建一个能够获取项目列表并返回(不打印!)该列表的字符串的函数,用逗号分隔'和'在列表中的最后一项之前。到目前为止我的脚本看起来像这样:

rose1 = Thing("red rose", "flowerbox")
rose2 = Thing("pink rose","garden")
rose3 = Thing("white rose", "vase")

def text_list(things):
    """Takes a sequence of Things and returns a formatted string that describes all of the things.

    Things -> string"""
    names=[o.name for o in things]
    if len(names) == 0:
        return 'nothing'
    elif len(names) == 2:
        names = ' and the '.join(names)
        return 'the ' + names
    else:   #Here's where I need help!
        names = ', the '.join(names)
        return 'the ' + names

所以在这一点上,该功能会返回红玫瑰,粉红玫瑰,白玫瑰和#34;这很棒,但我需要最后一次"和#34;要放在粉红玫瑰和白玫瑰之间,我不能用印花。有帮助吗?这可能很简单,我完全错过了OTL

1 个答案:

答案 0 :(得分:2)

检查以下内容是否满足您的要求。

names=[o.name for o in things[:-1]]
last_name = things[-1].name

使用“名称”列表的逻辑来获取result_string,最后将last_name附加到字符串中。

return result_string + ' and the ' + last_name