cashman04
cashman04

Reputation: 1173

Remove all blank lines from list python

I have the following results set as a variable. I need to remove all blank lines before I can make it a dictionary. What is a simple command I can run on a variable to remove all blank lines that may be contained in that variable. Below is an example of the output of my variable:

DeviceName = device1
ClientName = myclient
RegionName = west
PrimaryIP = 1.1.1.1
OsVersionName = Microsoft Windows 7 Enterprise
AccessMethod = None
AccessIP = None
Port = None


DeviceName = device2
ClientName = myclient
RegionName = None
PrimaryIP = 1.1.1.2
OsVersionName = Microsoft Windows 7 Enterprise
AccessMethod = None
AccessIP = None
Port = None

There is also a blank space at the beginning. I have tried a few different ways, but they only seem to remove the first blank line. I need to remove any and all blank lines that might appear in my results.

Upvotes: 0

Views: 1339

Answers (2)

jamylak
jamylak

Reputation: 133694

I'm not sure but this may be what you want:

>>> text = '''DeviceName = device1
ClientName = myclient
RegionName = west
PrimaryIP = 1.1.1.1
OsVersionName = Microsoft Windows 7 Enterprise
AccessMethod = None
AccessIP = None
Port = None


DeviceName = device2
ClientName = myclient
RegionName = None
PrimaryIP = 1.1.1.2
OsVersionName = Microsoft Windows 7 Enterprise
AccessMethod = None
AccessIP = None
Port = None'''
>>> text = '\n'.join(line for line in text.splitlines() if line)

But it would be much better to just ignore the blanks lines as you create your dictionary, using a generator expression:

>>> lines = (line for line in text.splitlines() if line)

Upvotes: 3

aldeb
aldeb

Reputation: 6838

txt = """DeviceName = device1
ClientName = myclient
RegionName = west
PrimaryIP = 1.1.1.1
OsVersionName = Microsoft Windows 7 Enterprise
AccessMethod = None
AccessIP = None
Port = None


DeviceName = device2
ClientName = myclient
RegionName = None
PrimaryIP = 1.1.1.2
OsVersionName = Microsoft Windows 7 Enterprise
AccessMethod = None
AccessIP = None
Port = None"""

print('\n'.join([i for i in txt.split('\n') if i]))

Output:

DeviceName = device1
ClientName = myclient
RegionName = west
PrimaryIP = 1.1.1.1
OsVersionName = Microsoft Windows 7 Enterprise
AccessMethod = None
AccessIP = None
Port = None
DeviceName = device2
ClientName = myclient
RegionName = None
PrimaryIP = 1.1.1.2
OsVersionName = Microsoft Windows 7 Enterprise
AccessMethod = None
AccessIP = None
Port = None

Upvotes: 0

Related Questions