从列表python中删除所有空行

时间:2013-04-17 00:05:53

标签: python

我将以下结果设置为变量。我需要删除所有空白行才能将其作为字典。什么是一个简单的命令我可以在变量上运行以删除该变量中可能包含的所有空行。下面是我的变量输出的示例:

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

开头还有一个空白区域。我尝试了几种不同的方法,但它们似乎只是删除了第一个空白行。我需要删除可能出现在结果中的所有空白行。

2 个答案:

答案 0 :(得分:2)

我不确定,但这可能是你想要的:

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

但是在使用生成器表达式创建字典时忽略空白行会好得多:

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

答案 1 :(得分:0)

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

输出:

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