Python 打印不带方括号和引号的列表
当输入以下代码时,我得到的正是我想要的输出:Python 打印不带方括号和引号的列表,python,python-3.x,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
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
我做错了什么?使用
sep
将分隔符放在所有参数之间,包括'List:'
和'Tuple:'
,因此您应该使用.join()
将列表/元组与,“
作为分隔符连接:
print('List : ', ",".join(List))
print('Tuple : ', ",".join(Tuple))
在print中使用“sep”会在其他两个参数之间插入分隔符
>>> print("a","b",sep="")
ab
试试这个:
>>> def print_sameline():
... list = [1,2,3]
... print("List: ",end="")
... print(*list,sep=",")
...
>>> print_sameline()
List: 1,2,3
你不认为它会计算初始字符串吗?