Adding spaces to items in list (Python)

我怕爱的太早我们不能终老 提交于 2019-11-29 11:41:24

As always, use a list comprehension:

lst = [' {0} '.format(elem) for elem in lst]

This applies a string formatting operation to each element, adding the spaces. If you use python 2.7 or later, you can even omit the 0 in the replacement field (the curly braces).

eumiro
[ ' {} '.format(x) for x in lst ]

EDIT for python 3.6+:

you can use f-strings instead, see docs: https://www.python.org/dev/peps/pep-0498/

the example above would look like:

[ f' {x} ' for x in lst ]
Prashant Kumar
lst = ['a', 'bb', 'c']  
lst = [' ' + x + ' ' for x in lst]
In [44]: l1 = ['a', 'bb', 'c']

In [45]: [' %s '%x for x in l1]
Out[45]: [' a ', ' bb ', ' c ']
waitingkuo

Indent your python code first! And then:

lst = ['a', 'b', 'c']
lst2 = [' ' + a + ' ' for a in lst]
print lst2

Try this:

lst = [' ' + x + ' ' for x in ['a', 'bb', 'c']]
>>> lst = ['a', 'bb', 'c']
>>> 
>>> [' {} '.format(x) for x in lst]
[' a ', ' bb ', ' c ']
>>> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!