Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding spaces to items in list (Python)

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.

like image 384
test123 Avatar asked Oct 15 '12 09:10

test123


People also ask

How do you put spaces between items in a list Python?

Use a formatted string literal to add a space between variables in Python, e.g. result = f'{var_1} {var_2}' . Formatted string literals allow us to include expressions inside of a string by prefixing the string with f .

How do you show spaces in a list in Python?

Python isspace() method is used to check space in the string. It returna true if there are only whitespace characters in the string. Otherwise it returns false. Space, newline, and tabs etc are known as whitespace characters and are defined in the Unicode character database as Other or Separator.


2 Answers

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

like image 121
Martijn Pieters Avatar answered Nov 02 '22 07:11

Martijn Pieters


[ ' {} '.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 ]
like image 38
eumiro Avatar answered Nov 02 '22 07:11

eumiro