Python 返回 false 表示 'dialog-bmp' 是 'dialog-bmp'



这里有学习的机会。我有一种情况,我正在更新文件中的某些属性。我有一个更新文件的函数:

def update_tiapp(property, value):
  print 'update_tiapp: updating "%s" to "%s"' % (property, value)
  for line in fileinput.input(os.path.join(app_dir, 'tiapp.xml')):  # , inplace=True
    if property is 'version':
      line = re.sub(r'(<version>).*?(</version>)', 'g<1>%sg<2>' % value, line.strip(), flags=re.IGNORECASE)
    elif property is 'brand':
      line = re.sub(r'(<property name="brand" type="string">).*?(</property>)', 'g<1>%sg<2>' % value, line.strip(), flags=re.IGNORECASE)'g<1>%sg<2>' % value, line.strip(), flags=re.IGNORECASE)
    elif property is 'banner-bmp':
      line = re.sub(r'(<banner-bmp>).*?(</banner-bmp>)', 'g<1>%sg<2>' % value, line.strip(), flags=re.IGNORECASE)
    elif property is 'dialog-bmp':
      line = re.sub(r'(<dialog-bmp>).*?(</dialog-bmp>)', 'g<1>%sg<2>' % value, line.strip(), flags=re.IGNORECASE)
    elif property is 'url':
      line = re.sub(r'(<url>).*?(</url>)', 'g<1>%sg<2>' % value, line.strip(), flags=re.IGNORECASE)

dialog-bmp &banner-bmp。由于某些我无法理解或找到的原因,条件就是不匹配。如果我将属性和条件更改为dialog, python很乐意匹配并为我进行更改。

窟? !

这是一个简单的改变,我不介意这样做,但我想了解。

为什么连字符会把一切都搞砸?我们这里不只是字符串匹配吗还是有什么我没有预料到的事情发生?

永远不要使用is来检查相等性(它检查对象的同一性)!使用==代替:

if property == "version":
    ...
elif property == "brand":
    ...
etc.

is可能适用于内部/缓存的短字符串,但前提是它们只包含对Python标识符("变量名")有效的字符。你的程序就是一个很好的例子:

>>> a = "dialog-bmp"
>>> b = "dialog-bmp"
>>> a is b
False
>>> id(a)
32571184L
>>> id(b)
32571088L
>>> a = "brand"
>>> b = "brand"
>>> a is b
True
>>> id(a)
32610664L
>>> id(b)
32610664L

相关内容

最新更新