首页 > 解决方案 > 我需要在列表中使用的 .join() 方法不适用于该列表中的最后两个值

问题描述

我正在解决 Automate The Boring Stuff In Python 中的练习项目,我目前在第 4 章。练习希望我将列表的内容变成字符串,并为倒数第二个值添加一个额外的值。

这是问题:

For practice, write programs to do the following tasks.
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns
a string with all the items separated by a comma and a space, with and
inserted before the last item. For example, passing the previous spam list to
the function would return 'apples, bananas, tofu, and cats'. But your func-
tion should be able to work with any list value passed to it.

到目前为止,我已经在一定程度上解决了这个问题,我只是想删除 .join() 方法中的分隔符,以免影响最后两个值。

我最初尝试使用end=',',但即使在最后一个值之后也放置了一个逗号。

这是我当前的代码:

def func(spam):
    spam.insert(-1, "and")
    print( ', '.join(spam))
    return spam


example = ["apples", "bananas", "tofu", "cats"]

func(example)
This is my current output:

PS C:\Users\DELL\Desktop\.py\AutomateTheBoringStuff\chapter_4\lists> python practice1.py    
apples, bananas, tofu, and, cats

预期的输出应该是:

apples, bananas, tofu and cats.

如果有比 join() 方法更好的方法,我将不胜感激。谢谢!

标签: pythonlistmethodsiteration

解决方案


推荐阅读