0

I am solving the practice projects in Automate The Boring Stuff In Python and I am currently in Chapter 4. The exercise expects me to make the contents of a list a string and add an extra value to the second to last value.

This is the question:

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.

So far, I have solved the question to an extent, I am just trying to remove the delimiter in the .join() method from affecting the last two values.

I initially tried using end=',', but it put a comma even after the last value.

This is my current code:

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

The expected output is supposed to be:

apples, bananas, tofu and cats.

If there's a better approach than the join() method, I'd really appreciate it. Thanks!

philipxy
  • 14,416
  • 5
  • 32
  • 77
Preshh0
  • 19
  • 2

0 Answers0