9

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.

7 Answers 7

15

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

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

This will give you ValueError: zero length field name in format
@BurhanKhalid: No it won't. Not in Python 2.7 where I tried it in any case.
@BurhanKhalid <2.7, yes. There make it ' {0} '. Pre 2.7, automatically numbering items wasn't possible.
' {0} '.format(x) would work in all versions where .format() is supported, hence a better answer.
2
lst = ['a', 'bb', 'c']  
lst = [' ' + x + ' ' for x in lst]

Comments

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

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

Comments

1

Indent your python code first! And then:

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

2 Comments

You'd be better off using the .format() method, or at a pinch the % string formatting operator, instead of concatenation. It is much more efficient.
This worked perfectly for every string I put in, thank you very much!
0

Try this:

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

3 Comments

You'd be better off using the .format() method, or at a pinch the % string formatting operator, instead of concatenation. It is much more efficient.
You can just replace ['a', 'bb', 'c'] with any other list of strings, or with a variable containing a list (e.g., your lst).
I agree, using .format() is a more efficient approach in terms of performance.
0
>>> lst = ['a', 'bb', 'c']
>>> 
>>> [' {} '.format(x) for x in lst]
[' a ', ' bb ', ' c ']
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.