自定义列表输出

时间:2019-05-22 06:37:51

标签: python python-3.x

我有这个列表:

sampleList=['a','b','c','d']

我需要显示如下列表元素:

a, b, c and d

我试图将','与每个列表元素连接在一起。但是我没有得到预期的结果。

','.join(sampleList)

每个列表元素在最后一个元素(例如a,b,c和d)之前用逗号和关键字“和”分隔。

3 个答案:

答案 0 :(得分:1)

没有内置的方法可以做到这一点。你必须自己动手

', '.join(sampleList[:-1]) + ' and ' + str(sampleList[-1])

输出:

>>> sampleList = ['a', 'b', 'c', 'd']
>>> ', '.join(sampleList[:-1]) + ' and ' + str(sampleList[-1])
'a, b, c and d'
>>>

答案 1 :(得分:0)

使用str.join尝试以下代码,并使用[::-1]str.replace进行反向操作(有点hack):

>>> sampleList=['a','b','c','d']
>>> s = ', '.join(sampleList)
>>> s[::-1].replace(' ,', ' dna ', 1)[::-1]
'a, b, c and d'
>>> 

答案 2 :(得分:0)

为此,您可以对n-1个元素执行相同的操作,并用'and'连接最后一个元素:

customer.summary
相关问题