如何在打印列表中的最后一个值之前添加字符串?

时间:2013-03-17 02:04:50

标签: list python-2.7

我是python(2.7.3)的新手,我正在尝试列表。假设我有一个定义为的列表:

my_list = ['name1', 'name2', 'name3']

我可以用以下方式打印:

print 'the names in your list are: ' + ', '.join(my_list) + '.'

哪个会打印:

the names in your list are: name1, name2, name3.

我如何打印:

the names in your list are: name1, name2 and name3.

谢谢。

更新

我正在尝试下面建议的逻辑,但以下是抛出错误:

my_list = ['name1', 'name2', 'name3']

if len(my_list) > 1:
    # keep the last value as is
    my_list[-1] = my_list[-1]
    # change the second last value to be appended with 'and '
    my_list[-2] = my_list[-2] + 'and '
    # make all values until the second last value (exclusive) be appended with a comma
    my_list[0:-3] = my_list[0:-3] + ', '

print 'The names in your list are:' .join(my_list) + '.'

2 个答案:

答案 0 :(得分:2)

试试这个:

my_list = ['name1', 'name2', 'name3']
print 'The names in your list are: %s, %s and %s.' % (my_list[0], my_list[1], my_list[2])

结果是:

The names in your list are: name1, name2, and name3.

%sstring formatting


如果my_list的长度未知:

my_list = ['name1', 'name2', 'name3']
if len(my_list) > 1: # If it was one, then the print statement would come out odd
    my_list[-1] = 'and ' + my_list[-1]
print 'The names in your list are:', ', '.join(my_list[:-1]), my_list[-1] + '.'

答案 1 :(得分:0)

我的两分钱:

def comma_and(a_list):
    return ' and '.join([', '.join(a_list[:-1]), a_list[-1]] if len(a_list) > 1 else a_list)

似乎在所有情况下都有效:

>>> comma_and(["11", "22", "33", "44"])
'11, 22, 33 and 44'
>>> comma_and(["11", "22", "33"])
'11, 22 and 33'
>>> comma_and(["11", "22"])
'11 and 22'
>>> comma_and(["11"])
'11'
>>> comma_and([])
''