Adding spaces to items in list (Python)

前端 未结 7 1878
北海茫月
北海茫月 2020-12-19 10:12

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

相关标签:
7条回答
  • 2020-12-19 10:25

    Try this:

    lst = [' ' + x + ' ' for x in ['a', 'bb', 'c']]
    
    0 讨论(0)
  • 2020-12-19 10:29
    lst = ['a', 'bb', 'c']  
    lst = [' ' + x + ' ' for x in lst]
    
    0 讨论(0)
  • 2020-12-19 10:31
    >>> lst = ['a', 'bb', 'c']
    >>> 
    >>> [' {} '.format(x) for x in lst]
    [' a ', ' bb ', ' c ']
    >>> 
    
    0 讨论(0)
  • 2020-12-19 10:39
    In [44]: l1 = ['a', 'bb', 'c']
    
    In [45]: [' %s '%x for x in l1]
    Out[45]: [' a ', ' bb ', ' c ']
    
    0 讨论(0)
  • 2020-12-19 10:41

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

    0 讨论(0)
  • 2020-12-19 10:42

    Indent your python code first! And then:

    lst = ['a', 'b', 'c']
    lst2 = [' ' + a + ' ' for a in lst]
    print lst2
    
    0 讨论(0)
提交回复
热议问题