2017-04-17 88 views
0

當進入下面的代碼我得到完全的輸出我想:打印列表標記

entrants = ['a','b','c','d'] 
# print my list with square brackets and quotation marks 
print (entrants) 

#print my list without brackets or quotes 
#but all on the same line, separated by commas 
print(*entrants, sep=", ") 

#print my list without brackets or quotes, each element on a different line 
#* is known as an 'identifier' 
print(*entrants, sep="\n") 

然而,當我輸入以下代碼:

values = input("Input some comma separated numbers: ") 
List = values.split(",") 
Tuple = tuple(List) 
print('List : ', List ) 
print('Tuple : ', Tuple) 
print('List : ', sep=",", *List ) 
print('Tuple : ', sep=",", *Tuple) 

我得到一個空間和逗號前的最後兩行輸出的第一個值如下:

List : ['1', '2', '3'] 
Tuple : ('1', '2', '3') 
List : ,1,2,3 
Tuple : ,1,2,3 

我該怎麼做錯了嗎?

+1

你不認爲它會算初始的字符串? –

回答

0

使用「SEP的「in print在另外兩個參數之間插入分隔符。

>>> print("a","b",sep="") 
ab 

試試這個:

>>> def print_sameline(): 
...  list = [1,2,3] 
...  print("List: ",end="") 
...  print(*list,sep=",") 
... 
>>> print_sameline() 
List: 1,2,3 
0

使用sep使分離去所有的參數之間包括'List : ''Tuple : ',所以你應該使用.join(),而不是加入列表/元組與","作爲分隔符:

print('List : ', ",".join(List)) 
print('Tuple : ', ",".join(Tuple)) 
+0

謝謝,它工作:) – sleepylog