-5

我有 2 个来自 xml 文件的变量;

编辑:*对不起。我粘贴了错误的值 * x="00 25 9E B8 B9 19 " y="F0 00 00 25 9E B8 B9 19 "

当我使用if x in y:声明时,什么都没有发生

但如果我使用if "00 25 9E B8 B9 19 " in y:我会得到结果

任何想法?


我正在添加我的完整代码;

import xml.etree.ElementTree as ET

tree =ET.parse('c:/sw_xml_test_4a.xml')
root=tree.getroot()

for sw in root.findall('switch'):



    for switch in root.findall('switch'):

        if sw[6].text.rstrip() in switch.find('GE01').text:
            print switch[0].text

        if sw[6].text.strip() in switch.find('GE02').text.strip():
            print switch[0].text

        if sw[6].text.strip() in switch.find('GE03').text.strip():
            print switch[0].text

        if sw[6].text.strip() in switch.find('GE04').text.strip():
            print switch[0].text    

xml 文件详细信息;

- <switch>
  <ci_adi>"aaa_bbb_ccc"</ci_adi> 
  <ip_adress>10.10.10.10</ip_adress> 
  <GE01>"F0 00 00 25 9E 2C BC 98 "</GE01> 
  <GE02>"80 00 80 FB 06 C6 A1 2B "</GE02> 
  <GE03>"F0 00 00 25 9E B8 BB AA "</GE03> 
  <GE04>"F0 00 00 25 9E B8 BB AA "</GE04> 
  <bridge_id>"00 25 9E B8 BB AA "</bridge_id> 
  </switch>
4

3 回答 3

4
>>> x = "00 25 9E 2C BC 8B"
>>> y = "F0 00 00 25 9E B8 B9 19"
>>> x in y
False
>>> "00 25 9E 2C BC 8B " in y
False

你到底是如何得到结果的?

让我解释一下什么in是检查。

in正在检查 的整个值x是否包含在 的值中的任何位置y。如您所见, 的整个值x并未全部包含在y.

但是,一些元素x是,也许你想要做的是:

>>> x = ["00", "25", "9E", "2C", "BC", "8B"]
>>> y = "F0 00 00 25 9E B8 B9 19"
>>> for item in x:
    if item in y:
        print item + " is in " + y


00 is in F0 00 00 25 9E B8 B9 19
25 is in F0 00 00 25 9E B8 B9 19
9E is in F0 00 00 25 9E B8 B9 19
于 2012-09-09T17:00:47.470 回答
1

运算符 in 和 not in 测试集合成员资格。如果 x 是集合 s 的成员,则 x in s 评估为 true,否则为 false。对于字符串,如果整个字符串 x 是 y 的子字符串,则返回 True,否则返回 False。

于 2012-09-09T17:02:22.427 回答
0

除了您问题中的值混淆之外,这似乎可以按照您想要的方式工作:

sxml="""\
<switch>
  <ci_adi>"aaa_bbb_ccc"</ci_adi> 
  <ip_adress>10.10.10.10</ip_adress> 
  <GE01>"F0 00 00 25 9E 2C BC 98 "</GE01> 
  <GE02>"80 00 80 FB 06 C6 A1 2B "</GE02> 
  <GE03>"F0 00 00 25 9E B8 BB AA "</GE03> 
  <GE04>"F0 00 00 25 9E B8 BB AA "</GE04> 
  <bridge_id>"00 25 9E B8 BB AA "</bridge_id> 
</switch>"""

tree=et.fromstring(sxml)
x="80 00 80 FB 06 C6 A1 2B"    # Note: I used a value of x I could see in the data; 
                               # your value of  x="00 25 9E B8 B9 19 " is not present...

for el in tree:
    print '{}: {}'.format(el.tag, el.text)
    if x in el.text:
        print 'I found "{}" by gosh at {}!!!\n'.format(x,el.tag)
于 2012-09-09T18:54:10.927 回答