如何在列表中的每个项目后添加换行符?

时间:2017-11-27 21:54:56

标签: python list

我有一些字符列表。当我打印它时,我得到以下输出:

['a', 'b', 'c', 'd', 'e']

但我想要的是:

['a',
 'b',
 'c',
 'd',
 'e']

我试过.join但是删除了[]和''而且我不想要那个。

任何帮助表示赞赏。我试图搜索但我只能找到.join解决方案。

由于

编辑:是否有可能以这种方式返回列表?或者只是打印出来?

4 个答案:

答案 0 :(得分:2)

您可以使用pprint(“漂亮打印”)模块:

from pprint import pprint
pprint(['a', 'b', 'c', 'd', 'e'], width=1)

如果您希望将值作为字符串获取而不是打印它,请使用pformat代替pprint

答案 1 :(得分:2)

这是使用Python 3中print执行此操作的一种hackish方式:

>>> print(*str(lst).split(','), sep=',\n')
['a',
 'b',
 'c',
 'd',
 'e']

答案 2 :(得分:2)

简单str.replace()方法:

lst = ['a', 'b', 'c', 'd', 'e']
print(repr(lst).replace(',', ',\n'))

输出:

['a',
 'b',
 'c',
 'd',
 'e']

答案 3 :(得分:0)

另一种可能的方式:

>>> ok = ['a', 'b', 'c', 'd', 'e']
>>> for x in ok.__repr__().split():
>>>     print(x)
...
... 
['a',
'b',
'c',
'd',
'e']

# py2
# for x in ok.__str__().split():print(x)