1

I have a list of strings returned after command execution, split on '\n'.

listname = output.decode('utf8').rstrip().split('\n')

When I print using print(listname), I get

['']

Clearly It's a list containing empty string

Because of this I am getting len(listname) as 1.

How to remove this empty string

  • 1
    You're looking for [`splitlines`](http://docs.python.org/2/library/stdtypes.html#str.splitlines). – georg May 14 '13 at 15:29

3 Answers3

5

I think this is what you are looking for:

filter(None,output.decode('utf8').rstrip().split('\n'))

In details:

>>> filter(None, ["Ford", "Nissan", ""])
['Ford', 'Nissan']

P.S. In python 3+ filter returns iterator, so use list(filter(..)).

Alexey Kachayev
  • 6,106
  • 27
  • 24
3
listname = [item for item in output.decode('utf8').rstrip().split('\n') if item]
Tim
  • 19,793
  • 8
  • 70
  • 95
1
output = output.decode('utf8').rstrip()
if output:
    listname = []
else:
    listname = output.split('\n')
Remco Haszing
  • 7,178
  • 4
  • 40
  • 83