items=['a', 'b', 'c', 'd', 'e']
print("The first 3 items in the list are: ")
for item in items[:3]:
print(item)
#or
print("The first 3 items in the list are: " + str(items[:3]))
问:如何使“前 3 项”的输出是水平的(如第二个代码)但没有方括号(如第一个代码)?
最佳答案
您可以使用str.join(iterable)
,其中 str
是 iterable
中项目之间的分隔符。例如:
items = ['a', 'b', 'c', 'd', 'e']
print('The first 3 items in the list are: ' + ', '.join(items[:3]))
打印:
The first 3 items in the list are: a, b, c
在本例中,', '
是列表项之间的分隔符。您可以根据您的需要更改它。例如,使用 ' '.join(items[:3])
会导致:
The first 3 items in the list are: a b c
关于python - 如何删除列表输出中的方括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60221314/