gpt4 book ai didi

linux - python : Removing white spaces between two string entries in a list

转载 作者:太空宇宙 更新时间:2023-11-04 04:15:15 25 4
gpt4 key购买 nike

这是代码:

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"']

除了第一个列表的两个条目之间的空格之外,这两个列表是相同的。因此,比较给出了错误的值。如何删除那个空白?请帮忙。预先感谢您。

最佳答案

您正在剥离空行;使用简单的 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]

关于linux - python : Removing white spaces between two string entries in a list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16786539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com