[英]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)
,其中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
有幾種方法。 適當的這里(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.