I\'m working through \'Automate the Boring Stuff with Python\'. I can\'t figure out how to remove the final output comma from the program below. The goal is to keep promptin
You can avoid adding commas to each string in the list by deferring the formatting to print time. Join all the items excluding the last on ', ', then use formatting to insert the joined string with the last item conjuncted by and:
listed.append(inputed)
...
print('{}, and {}'.format(', '.join(listed[:-1]), listed[-1]))
Demo:
>>> listed = ['a', 'b', 'c', 'd']
>>> print('{}, and {}'.format(', '.join(listed[:-1]), listed[-1]))
a, b, c, and d
Lots of ways to do it, but how about this?
# listed[-1] is the last element of the list
# rstrip removes matching characters from the end of the string
listed[-1] = listed[-1].rstrip(',')
listed.insert(-1, 'and')
for i in listed:
print(i, end=' ')
You'll still be printing a space at the end of the line, but I guess you won't see it and thus won't care. :-)
Modifying your code a little bit...
def lister():
listed = []
while True:
print('type what you want to be listed or type nothing to exit')
inputted = input()
if inputted == '':
break
else:
listed.append(inputted) # removed the comma here
print(', '.join(listed[:-2]) + ' and ' + listed[-1]) #using the join operator, and appending and xxx at the end
lister()
listed[-1] = listed[-1][:-1]
This will truncate the final character of the final string in listed.
I would do it using an f-string (a formatted string literal, available in Python 3.6+):
def grammatically_join(words, oxford_comma=False):
if len(words) == 0:
return ""
if len(words) == 1:
return listed[0]
if len(words) == 2:
return f"{listed[0]} and {listed[1]}"
return f'{", ".join(words[:-1])}{"," if oxford_comma else ""} and {words[-1]}'
If you don't need the Oxford comma, then you can simplify the code and remove the extra edge case for len(words) == 2:
def grammatically_join(words):
if len(words) == 0:
return ""
if len(words) == 1:
return listed[0]
return f'{", ".join(words[:-1])} and {words[-1]}'
The accepted answer is good, but it might be better to move this functionality into a separate function that takes a list, and also handle the edge cases of 0, 1, or 2 items in the list:
def oxfordcomma(listed):
if len(listed) == 0:
return ''
if len(listed) == 1:
return listed[0]
if len(listed) == 2:
return listed[0] + ' and ' + listed[1]
return ', '.join(listed[:-1]) + ', and ' + listed[-1]
Test cases:
>>> oxfordcomma([])
''
>>> oxfordcomma(['apples'])
'apples'
>>> oxfordcomma(['apples', 'pears'])
'apples and pears'
>>> oxfordcomma(['apples', 'pears', 'grapes'])
'apples, pears, and grapes'