2013-03-17 39 views
-1

我是新來的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.

謝謝。 PS:我試圖提交這個,它是說'這篇文章不符合我們的質量標準'。上述帖子需要改進的地方是什麼?

更新:

我想邏輯如下建議,但下面是引發錯誤:

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) + '.' 
+0

至於你PS,我編輯的問題,使其更清潔 – TerryA 2013-03-17 02:50:58

回答

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] + '.' 
+0

謝謝,這將意味着(也許我應該提到這一點)列表中的項目數量是已知的數量 - 如果列表是動態的,並且需要給出的'指令'是'將所有項目分開一個逗號,除了最後一個值,你用'和'分隔它(這意味着第二個值在它後面沒有逗號)。我想我以後的功能有點像css中的'最後一個孩子'概念。 – user1063287 2013-03-17 06:21:02

+0

@ user1063287我編輯了我的答案 – TerryA 2013-03-17 06:37:39

+0

謝謝,第二個值後面仍然有一個逗號,所以它現在看起來像'名單中的名字是name1,name2和name3'。 – user1063287 2013-03-17 07:15:40

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([]) 
'' 
相關問題