Python:删除列表中两个字符串条目之间的空格

时间:2013-05-28 07:45:26

标签: linux list python-2.7

这是代码:

import os
import re
import subprocess

current_setting = list()
with open('/etc/init/control-alt-delete.conf' ,'r')as fp:
    for line in fp:
        if not line.startswith('#'):
            current_setting.append(line.strip())
current_setting.remove('')
print current_setting

desired_setting = list()
with open('ctl_alt_del', 'r') as f:
    for line in f:
        desired_setting.append(line.strip())
print desired_setting

if set(current_setting) == set(desired_setting):
    print 'The file has to be modified'

我的输出为:

['start on control-alt-delete', '', 'exec /sbin/shutdown -r now "Control-Alt-Delete pressed"']
['start on control-alt-delete', 'exec /sbin/shutdown -r now "Control-Alt-Delete pressed"']

除了第一个列表的两个条目之间的空格之外,这两个列表是相同的。 因此,比较是假的。 如何删除那个空白区域?请帮忙。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

你正在剥离空行;使用简单的if跳过它们:

with open('ctl_alt_del', 'r') as f:
    for line in f:
        if line.strip():
            desired_setting.append(line.strip())

您可以使用列表解析来简化这些行:

with open('ctl_alt_del', 'r') as f:
    desired_setting = [line.strip() for line in f if line.strip()]

(现在不需要在这些行之前使用desired_setting = list()。)

或者,在事实之后过滤行:

desired_setting = filter(None, desired_setting)

desired_setting = [line for line in desired_setting if line]