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
  • 1
    You're looking for splitlines. Commented May 14, 2013 at 15:29

3 Answers 3

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

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

2 Comments

+1 but I had to use list(filter(None,...)) again
@Drt Good point, updated my answer.
3
listname = [item for item in output.decode('utf8').rstrip().split('\n') if item]

Comments

1
output = output.decode('utf8').rstrip()
if output:
    listname = []
else:
    listname = output.split('\n')

1 Comment

+1, although I'd use a conditional: lst = out.split('\n') if out else []