我需要导入什么才能在python中使用index()?

时间:2016-10-14 07:23:47

标签: python

我打电话跟随功能,

    import clr
    import System
    import ServiceDesk
    import BaseModel
    class Model(BaseModel.Model):
      def ExecuteCustomAction(self,args,env):
        resault = self.account.ExecuteService('service',args,env)
        res = {}
        if resault.Count>0:
            for customaction in resault.Rows:
                CustomActions = customaction['CustomActions']
                if CustomActions !="":
                    Lable = self.find_between( CustomActions, "Lable", "d" )
                    CallBack = self.find_between( CustomActions, "CallBack", ";" )
                    Action = self.find_between( CustomActions, "Action", "f" )
                    res['Lable'] = Lable
                    res['CallBack'] = CallBack
                    res['Action'] = Action
        return res

    def find_between( text, first, last ,self):
        try:
            start = text.index( first ) + len( first )
            end = text.index( last, start )
            return text[start:end]

        except ValueError:
            return ""

但是当我执行此操作时,它会说

  

对象没有属性'index'

我需要导入什么?

1 个答案:

答案 0 :(得分:2)

当您传递的text值不正确时,会出现此错误。 text必须是一个字符串,索引方法才能正常工作。例如:

>>> def find_between( text, first, last ,self):
...     try:
...         start = text.index( first ) + len( first )
...         end = text.index( last, start )
...         return text[start:end]
...     except ValueError:
...         return ""
... 
>>> find_between("some_string", "s", "t", None)
'ome_s'

>>> find_between(123, "s", "t", None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in find_between
AttributeError: 'int' object has no attribute 'index'

>>> find_between(None, "s", "t", None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in find_between
AttributeError: 'NoneType' object has no attribute 'index'

在您使用的代码中,最有可能的是,CustomActions是一个对象,而不是一个字符串。将对象传递给函数时,您将收到错误,因为它不是字符串。您可以使用type(CustomActions)检查其类型,以验证其不是字符串。

另外,请注意self必须是第一个参数,因此您的签名应该如下所示:

def find_between(self, text, first, last):