使用find()方法时发生AttributeError

时间:2018-08-31 23:16:01

标签: python

希望有人可以对此提供解释...

我是Python的新手,偶然发现了这份作业(通过在线课程学习):

创建了卡片组,需要删除几张卡片-以为我在卡片组[。]中找到.find(str),返回其索引(i)和.remove(i)。这样,由于我仍在学习,因此可以验证代码的工作方式。

使用.find()方法时,出现以下错误:
AttributeError: 'list' object has no attribute 'find'

但是在索引方法上没有这样的错误:这是两种方法。

`

def indxcard(self,fcard):
    '''

    :return index of -1 if not found

    '''
    retval=-1

    try:
        retval=self.Carddeck.index(fcard)

    except:
        # value not found
        retval = -1

    # print only for debugging
    print('in Indxcard', retval,fcard)
    return retval

def findcard(self, fcard):
    '''
    :return index of card -1 if not found

    '''
    retval = self.Carddeck.find(fcard)  # Causes an attribute error...
    print('in find card', retval, fcard)
    return retval

...和调用代码...

print(gamedeck)
print('-----------')
for killzerocard in Cards.Suits:
    # gamedeck.killcard('0'+killzerocard[1:])  # Uno deck only as 1  Zero (0) card for each of the colors

    try:
        gamedeck.findcard('0'+killzerocard)
    except:
        print('error thrown by find')

    gamedeck.indxcard('0'+killzerocard)

print('-----------')

# gamedeck.shuffle()
print(gamedeck)

`

和结果:

enter image description here

1 个答案:

答案 0 :(得分:1)

list对象没有find方法。 strlist对象都具有index方法,但是只有str具有find方法。对于字符串,这两种方法在很大程度上相似,不同之处在于,当字符串中不存在参数时,index将引发异常,而find将返回-1