繁体   English   中英

如何删除列表输出中的方括号?

[英]How to remove the square brackets in output of the list?

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) ,其中striterable项目之间的分隔符。 例如:

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

有几种方法。 适当的这里(IMO)是使用

print("items are: " + ', '.join(items[:3]))

其中(取决于您的python版本)可以简化为:

print(f'items are: {", ".join(items[:3])}')

或者没有逗号

另一种方法是告诉print不打印换行符:

for item in items[:3]:
    print(item, end='')

您可以在循环中编写print(item, end=" ")

这样做:

print("The first 3 items in the list are: " + str(items[:3])[1:-1])

假设您不介意以逗号分隔的项目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM