0

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

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

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

4

2 回答 2

3

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

>>> 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)
于 2013-04-17T00:06:47.130 回答
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
于 2013-04-17T00:10:03.080 回答