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.
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 .
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.
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).
[ ' {} '.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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With