gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:02:45 26 4
gpt4 key购买 nike

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

关于python - 如何删除列表输出中的方括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60221314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com