I am working with Python 3.2 and I have a list where the elements may vary in number depending on the original input. How can I print the elements from the list, but add 'and' before the last element when I don't know the exact number of elements in the list?
3 Answers
For a list called floep
print('%s and %s' % (', '.join(floep[:-1]), floep[-1]))
As commented, a mapping might be needed for non-strings
print('%s and %s' % (', '.join(str(x) for x in floep[:-1]), floep[-1]))
4 Comments
IamAlexAlright
I'm not familiar with python 3.2 so I could be totally off base though but will ''.join work on a list of ints? I have to map(str,list) before I can join in python2.7
James Waldby - jwpat7
Saying
map(lambda x: str(x), ... when you can say map(str, ... looks kind of silly.Mark
Okay how's this?
[str(x) for x in floep[:-1]] Prettier?satoru
I would use a generator expression like this:
','.join(str(x) for x in floep[:-1]).
[1, 2, 3, 4, 5]is1, 2, 3, 4 and 5?