ElementTree解析XML时==与in比较操作的差异疑问
in与==在字符串比较中的差异解析 先看你给出的XML片段:
<metaMetadata> <metadataSchema>Value1</metadataSchema> <metadataSchema>Value2</metadataSchema> </metaMetadata>
以及对应的Python代码:
schema_val = ['Value1', 'Value2'] for ele in root.findall(".//{*}metaMetadata"): m_schema = ele.findall("lom:metadataSchema",ns) m_schema_check = [i for i in schema_val if i in m_schema[0].text] if m_schema_check: for i in m_schema_check: schema_val.remove(i) if m_schema[1].text in schema_val: print('pass')
核心差异点
in:子串包含检查A in B判断的是字符串A是否是字符串B的子部分,只要B里能找到连续的A字符序列就返回True。比如'Value1' in ' Value1 '或者'Value1' in '\nValue1\n'都会返回True。==:完全相等检查A == B要求两个字符串的每一个字符都完全一致,包括长度、可见字符、隐藏的空白符(空格、换行、制表符等),只有完全匹配才返回True。
你的代码场景分析
换成==后无法触发print,大概率是因为XML解析后,m_schema[0].text和m_schema[1].text并不是纯粹的'Value1'或'Value2'——XML元素的文本内容会保留缩进的空格、换行符等空白字符。比如实际打印出来的m_schema[0].text可能是' Value1'或者'\n Value1\n '。
这时候:
- 用
i in m_schema[0].text:因为'Value1'是带空白的字符串的子串,所以判断成立,能生成m_schema_check并进入后续逻辑。 - 用
i == m_schema[0].text:因为两边字符串不完全一致(多了空白),判断不成立,m_schema_check为空,后续的print自然不会执行。
验证与修复方法
你可以用repr()函数打印出字符串的真实内容,确认是否包含空白字符:
print(repr(m_schema[0].text)) print(repr(m_schema[1].text))
如果确实有空白,可以先用strip()方法去除前后空白再做相等比较:
m_schema_check = [i for i in schema_val if i == m_schema[0].text.strip()]
内容的提问来源于stack exchange,提问作者Avila
相关产品推荐
相关产品推荐

