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?
Thanks
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