def print_nicely(iterable): iterable = list(map(str, iterable)) if len(iterable) > 1: print(f"'{', '.join(iterable[:-1])} and {iterable[-1]}'") elif len(iterable) == 1: print(f"'{iterable[0]}'") else: raise ValueError('Expecting non-empty iterable') print_nicely(['apples', 'bananas', 'tofu', 'cats']) # print list print_nicely(['bird']) # print single element list print_nicely(range(4)) # print range object print_nicely([])
Output:'apples, bananas, tofu and cats'
'bird'
'0, 1, 2 and 3'
Traceback (most recent call last):
File "***", line 13, in <module>
print_nicely([])
File "***", line 8, in print_nicely
raise ValueError('Expecting non-empty iterable')
ValueError: Expecting non-empty iterable
by the way i may have seen a package on PyPI that does it but cannot find it at the moment
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs