打印列表没有方括号和引号

时间:2017-04-17 03:39:21

标签: python python-3.x

输入以下代码时,我得到了我想要的输出:

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

我做错了什么?

2 个答案:

答案 0 :(得分:0)

使用sep使分隔符介于包括'List : ''Tuple : '在内的所有参数之间,因此您应该使用.join()来加入List / Tuple并使用{{ 1}}作为分隔符:

","

答案 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