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?
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]))
for a list, a
a = map(str, a)
print(', '.join(a[:-1]) + ', and ' + a[-1])
edit: I believe IamAlexAlright was right about needing a map
first
Try this:
for i in range(len(list)):
if i=len(list)-2:
print('and')
print(len[i])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.