Currently working my way through this beginners book and have completed one of the practice projects \'Comma Code\' which asks the user to construct a program which:
I didn't dig through all the answers but I did see someone suggested using join. I agree but since this question didn't come in the book before learning joins my answer was this.
def To_String(my_list)
try:
for index, item in enumerate(my_list):
if index == 0: # at first index
myStr = str(item) + ', '
elif index < len(my_list) - 1: # after first index
myStr += str(item) + ', '
else:
myStr += 'and ' + str(item) # at last index
return myStr
except NameError:
return 'Your list has no data!'
spam = ['apples', 'bananas', 'tofu', 'cats']
my_string = To_String(spam)
print(my_string)
Result:
apples, bananas, tofu, and cats