Adding spaces to items in list (Python)
Solution 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).
Solution 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 ]
Solution 3
lst = ['a', 'bb', 'c']
lst = [' ' + x + ' ' for x in lst]
Solution 4
In [44]: l1 = ['a', 'bb', 'c']
In [45]: [' %s '%x for x in l1]
Out[45]: [' a ', ' bb ', ' c ']
Solution 5
Indent your python code first! And then:
lst = ['a', 'b', 'c']
lst2 = [' ' + a + ' ' for a in lst]
print lst2
test123
Updated on July 09, 2022Comments
-
test123 almost 2 years
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.
-
Burhan Khalid over 11 yearsThis will give you
ValueError: zero length field name in format
-
Martijn Pieters over 11 years@BurhanKhalid: No it won't. Not in Python 2.7 where I tried it in any case.
-
Gareth Latty over 11 years@BurhanKhalid <2.7, yes. There make it
' {0} '
. Pre 2.7, automatically numbering items wasn't possible. -
Burhan Khalid over 11 years
' {0} '.format(x)
would work in all versions where.format()
is supported, hence a better answer. -
Martijn Pieters over 11 yearsYou'd be better off using the
.format()
method, or at a pinch the%
string formatting operator, instead of concatenation. It is much more efficient. -
Martijn Pieters over 11 yearsYou'd be better off using the
.format()
method, or at a pinch the%
string formatting operator, instead of concatenation. It is much more efficient. -
Anton Beloglazov over 11 yearsYou can just replace
['a', 'bb', 'c']
with any other list of strings, or with a variable containing a list (e.g., yourlst
). -
test123 over 11 yearsThis worked perfectly for every string I put in, thank you very much!
-
Anton Beloglazov over 11 yearsI agree, using
.format()
is a more efficient approach in terms of performance. -
test123 over 11 yearsThank you for the explanation, perfect!