当前位置: 代码迷 >> python >> 在仅包含空格的列表中区分字符串
  详细解决方案

在仅包含空格的列表中区分字符串

热度:26   发布时间:2023-06-27 21:53:46.0

我正在尝试创建一个if语句,该语句可以区分列表中的两个字符串,唯一的区别是它们之前的空白量。

由于某种原因,我无法使其中任何一个正常工作。

with open(os.path.dirname(os.path.realpath(__file__)) + "\defaults\handling.meta") as file:
contents = file.readlines()

for index, item in enumerate(contents):
    if ("    </Item>" in item) and (index > old_start_lines[0]):

这不能区分

        </Item>

(8个空格)和

    </Item>

(4个空格)。 像这样添加长度检查会产生错误:

    and (len(contents[index]) == 11):

这另外两个检查也分别导致未区别的结果和相同的错误。

    if (item.startswith("    </Item>")) and (index > old_start_lines[0]):
    if ("    </Item>" == item) and (index > old_start_lines[0]):

错误是:

IndexError:列表索引超出范围

这是我正在使用的文本文件->列表的示例: :

谢谢,

阿尔菲

编辑:完整项目-https://drive.google.com/file/d/1hcs1zkAu5xBWJYhZ97UXUcEkPdo-yQ4m/view

一种简单的解决方法是在输入字符串的左侧去除空格:

if ("</Item>" in item.lstrip())

您还可以使用.strip()或.rstrip(),请参见

您需要使用Python的来使正则表达式与空格完全匹配。

import re
with open('FilePath') as file:
contents = file.readlines()
regex = re.compile(r"^\s{8}<\/Item>")
#for 4 spaces you can replace 8 with 4


for index, item in enumerate(contents):
    if (bool(regex.search(item))):
        print (item)
        print('</Item> with 8 spaces')

输出:

        </Item>

</Item> with 8 spaces
  相关解决方案