[英]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]))
Q: How should I make the output of the 'first 3 items' to be horizontal(like the second code) but without the square brackets(like the 1st code)?问:我应该如何使“前 3 个项目”的输出水平(如第二个代码)但没有方括号(如第一个代码)?
You can use str.join(iterable)
, where str
is the separator between the items in the iterable
.您可以使用
str.join(iterable)
,其中str
是iterable
项目之间的分隔符。 For example:例如:
items = ['a', 'b', 'c', 'd', 'e']
print('The first 3 items in the list are: ' + ', '.join(items[:3]))
This prints:这打印:
The first 3 items in the list are: a, b, c
In this case, ', '
is the separator between the items of the list.在这种情况下,
', '
是列表项之间的分隔符。 You can change it according to your needs.您可以根据需要更改它。 For example, using
' '.join(items[:3])
instead would result in:例如,使用
' '.join(items[:3])
会导致:
The first 3 items in the list are: a b c
There are several ways.有几种方法。 The appropriate here (IMO) is to use
适当的这里(IMO)是使用
print("items are: " + ', '.join(items[:3]))
Which (depending on your python version) can be simplified to:其中(取决于您的python版本)可以简化为:
print(f'items are: {", ".join(items[:3])}')
or without the comma或者没有逗号
Another way is to tell the print
to not print linebreaks:另一种方法是告诉
print
不打印换行符:
for item in items[:3]:
print(item, end='')
您可以在循环中编写print(item, end=" ")
。
This would do it:这样做:
print("The first 3 items in the list are: " + str(items[:3])[1:-1])
assuming you don't mind the items separated by commas.假设您不介意以逗号分隔的项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.