1

I'm starting out in Python and going through the book: Automate The Boring Stuff With Python.

I'm doing an exercise in chapter 4 called Comma Code. I'm supposed to be able to create a simple function that can take any list no matter what length e.g. ['apples','bananas','tofu','cats'] and output as: apples, bananas, tofu, and cats; the key being able to insert the word and between the last and second to last list value

I have written something which works (see below). But it outputs the values in new lines rather than on one line.

'''Practice Projects - Comma Code'''

def commacode(list_range):
    for i in range(len(list_range)):
        #print(i)
        position = len(list_range) - i
        #print(position)
        list_a = ''
        list_b = ''
        if position != 1:
            #list = ''
            list_a += str(list_range[i]) + ','
            print(list_a)
        else:
            list_b += list_a + ' and ' + str(list_range[i])
    print(list_a + list_b)

rangeoflist = ['apples','bananas','tofu','cats']
commacode(rangeoflist)
#print(rangeoflist)

How can I get an output on one line?

enter image description here

Thanks

khelwood
  • 55,782
  • 14
  • 81
  • 108
Shaye
  • 179
  • 13
  • `print(rangeoflist[:-1], f'and {rangeoflist [-1]}',sep = ", ")` ? – Patrick Artner Sep 11 '20 at 19:31
  • @Patrick Artner. Thanks. This was kinda alright but it returns a list value hence it still looks like a list. Output: ['apples', 'bananas', 'tofu'], and cats. I could probably strip out the "]" and "[" – Shaye Sep 14 '20 at 00:16
  • `print(*rangeoflist[:-1], f'and {rangeoflist [-1]}',sep = ", ")` - missed an asterix – Patrick Artner Sep 14 '20 at 05:25

2 Answers2

2

To print the sentence in one line, add end='' to first print():

'''Practice Projects - Comma Code'''

def commacode(list_range):
    for i in range(len(list_range)):
        position = len(list_range) - i
        list_a = ''
        list_b = ''
        if position != 1:
            list_a += str(list_range[i]) + ','
            print(list_a, end='')                  # <-- add end='' here
        else:
            list_b += list_a + ' and ' + str(list_range[i],)
    print(list_a + list_b)

rangeoflist = ['apples','bananas','tofu','cats']
commacode(rangeoflist)

Prints:

apples,bananas,tofu, and cats

Simpler code can be achieved by using str.join. For example:

rangeoflist = ['apples','bananas','tofu','cats']
print(','.join(rangeoflist[:-1]) + ' and ' + rangeoflist[-1])

Prints:

apples,bananas,tofu and cats
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    Thanks @Andrej Kesely. A little bit of progress in my Python journey. https://www.geeksforgeeks.org/gfact-50-python-end-parameter-in-print/. I liked your simpler code. That may be the answer to this exercise actually. – Shaye Sep 14 '20 at 00:09
2

Python is quite elegant, when it comes to strings. I use join and array slicing.

rangeoflist = ['apples','bananas','tofu','cats']
solution = " and ".join([", ".join(rangeoflist[:-1]), rangeoflist[-1]])
print(solution)

That's all code you need.

jorop
  • 483
  • 4
  • 4