Adding spaces to items in list (Python)

回眸只為那壹抹淺笑 提交于 2019-12-07 07:49:27

问题


I'm a Python noob and I need some help for a simple problem.

What I need to do is create a list with 3 items and add spaces before and after every item.

For example: l1 = ['a', 'bb', 'c']
should be transformed into: [' a ',' bb ',' c ']

I was trying to write something like this:

lst = ['a', 'bb', 'c']
for a in lst:
    print '  a  '

...and so on for the other elements, but I get a syntax error. Can anyone suggest me a working way to do this? Thanks.


回答1:


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).




回答2:


[ ' {} '.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 ]



回答3:


lst = ['a', 'bb', 'c']  
lst = [' ' + x + ' ' for x in lst]



回答4:


In [44]: l1 = ['a', 'bb', 'c']

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



回答5:


Indent your python code first! And then:

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



回答6:


Try this:

lst = [' ' + x + ' ' for x in ['a', 'bb', 'c']]



回答7:


>>> lst = ['a', 'bb', 'c']
>>> 
>>> [' {} '.format(x) for x in lst]
[' a ', ' bb ', ' c ']
>>> 


来源:https://stackoverflow.com/questions/12892698/adding-spaces-to-items-in-list-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!