在Python中,我需要导入什么来使用index()函数?

2024-04-29 14:56:29 发布

您现在位置: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 ""

但当我执行这个时,它说

object has no attribute 'index'

我需要导入什么?在


Tags: textimportselfindexreturncallbackresaction
1条回答
网友
1楼 · 发布于 2024-04-29 14:56:29

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

>>> 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必须是第一个参数,因此签名应该如下所示:

^{pr2}$

相关问题 更多 >