迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中 AttributeError: 'list' object has no attribute 'find' 错误

作者:迹忆客 最近更新:2023/01/03 浏览次数:

当我们尝试在列表而不是字符串上调用 find() 方法时,会出现 Python“**AttributeError: 'list' object has no attribute 'find'**”。

如果我们需要检查一个值是否在列表中,请使用 in,如果我们需要获取列表中某个值的索引,请使用 index() 方法。

下面是产生上述错误的示例代码

my_list = ['apple', 'banana', 'kiwi']

# ⛔️ AttributeError: 'list' object has no attribute 'find'
print(my_list.find('banana'))

Python 中 AttributeError- 'list' object has no attribute 'find'

我们创建了一个包含 3 个元素的列表,并尝试对其调用 find() 方法,这导致了错误,因为 find() 是一个字符串方法。

如果需要检查某个值是否在列表中,请使用 in 运算符。

my_list = ['apple', 'banana', 'kiwi']

if 'banana' in my_list:
    print('banana is in the list') # 👉️ this runs
else:
    print('banana is not in the list')

如果需要获取列表中某个值的索引,请使用 index() 方法。

my_list = ['apple', 'banana', 'kiwi']

result = my_list.index('banana')

print(result)  # 👉️ 1

list.index() 方法返回其值等于提供的参数的第一个项目的索引。

如果列表中没有这样的项目,该方法会引发 ValueError

我们可以使用 try/except 语句来处理项目不在列表中的情况。

my_list = ['apple', 'banana', 'kiwi']


try:
    result = my_list.index('melon')
    print(result)
except ValueError:
    print('item is not in the list')  # 👉️ this runs

如果我们打算对列表中的字符串调用 find() 方法,则必须访问特定索引处的列表或对其进行迭代。

my_list = ['apple', 'banana', 'kiwi']

result = my_list[0].find('l')

print(result)  # 👉️ 3

我们访问索引 0 处的列表并调用 find() 方法来获取字符串中第一次出现的子字符串的索引。

如果我们只需要检查是否在字符串中找到子字符串,请使用 in 运算符。

my_list = ['apple', 'banana', 'kiwi']

if 'ppl' in my_list[0]:
    print('ppl is contained in apple')

str.find() 方法返回字符串中提供的子字符串第一次出现的索引。

如果在字符串中找不到子字符串,则该方法返回 -1

如果需要对列表中的每个字符串调用方法,请使用 for 循环遍历列表。

my_list = ['apple', 'banana', 'kiwi']

for word in my_list:
    result = word.find('a')
    print(result)  # 👉️ 0, 1, -1

当我们尝试在列表而不是字符串上调用 find() 方法时,会出现“AttributeError: 'list' object has no attribute 'find' ”。

我们可以使用 dir() 函数查看对象具有的所有属性。

my_list = ['a', 'b', 'c']

# 👉️ [... 'append', 'clear', 'copy', 'count', 'extend', 'index',
#  'insert', 'pop', 'remove', 'reverse', 'sort' ...]
print(dir(my_list))

如果将一个类传递给 dir() 函数,它会返回该类属性的名称列表,并递归地返回其基类的属性。

如果我们尝试访问不在此列表中的任何属性,我们将收到“**AttributeError:'list' object has no attribute 'find'**”错误。

由于 find() 不是列表实现的方法,所以导致错误。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便