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

标签 python python-3.x

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/

相关文章:

python - 如何修复 python3.4 中没有名为 parse 的模块

python - 检查一个数字是否是第二个数字的倍数

python - 如何禁用 nosetest 插件

python-3.x - 这是在 Python 3 中从 URL 获取图像的正确方法吗?

python - 如何从 Python 装饰器内部访问装饰方法局部变量( locals() )?

python - 通过 Python 进行音频/视频广播

python - 如何使 python 模拟函数返回一个特定的值以函数的参数为​​条件?

python - 如何检索用户在终端中输入的文本(但在用户按下回车键之前)

python - jupyter 笔记本 vs jupyter 控制台 : display of markdown (and latex, html 等)对象

python - 即使输出完美,Python 中也会出现不匹配错误