【发布时间】:2018-03-31 18:08:40
【问题描述】:
如何在每个列表元素之间添加一个逗号,在最后两个元素之间添加一个“and”,这样输出将是:
My cats are: Bella
My cats are: Bella and Tigger
My cats are: Bella, Tigger and Chloe
My cats are: Bella, Tigger, Chloe and Shadow
这是我的两个功能,都不能正常工作:
Example = ['Bella', 'Tigger', 'Chloe', 'Shadow']
def comma_and(list):
for i in range(len(list)):
print('My Cats are:',', '.join(list[:i]), 'and', list[-1],)
def commaAnd(list):
for i in range(len(list)):
print('My Cats are:',', '.join(list[:i]), list.insert(-1, 'and'))
我目前的输出是:
>> comma_and(Example)
My Cats are: and Shadow
My Cats are: Bella and Shadow
My Cats are: Bella, Tigger and Shadow
My Cats are: Bella, Tigger, Chloe and Shadow
>> commaAnd(Example)
My Cats are: None
My Cats are: Bella None
My Cats are: Bella, Tigger None
My Cats are: Bella, Tigger, Chloe None
【问题讨论】:
-
你得到了什么输出?
标签: python list code-formatting