使用 print() 函数显示带有自定义分隔符的列表项

Display list items with custom separator using print() function

有人可以向我解释为什么当我尝试使用星号将解压缩数据传递到打印函数时,可选参数 "end" 仅适用于最后一个列表的元素,而其余的是默认值 ( space)

l = ['a', 'b', 'c']
print(*l, end='-')

我预计 a-b-c- 而不是 a b c-

根据 print() docs

Print objects to the text stream file, separated by sep and followed by end.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.

sep参数用于控制print参数之间的分隔符。 end 只控制行结束符。

l = ['a', 'b', 'c']
print(*l, sep='-', end='-')
# a-b-c-

除了之前的答案,您可能会发现以下内容也很有用:

>>> l = ['a', 'b', 'c']
>>> print('-'.join(l) + '-')
a-b-c-