Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找和索引之间的差异_Python_String_Python 2.7 - Fatal编程技术网

Python 查找和索引之间的差异

Python 查找和索引之间的差异,python,string,python-2.7,Python,String,Python 2.7,我是python新手,不能完全理解find和index之间的区别 >>> line 'hi, this is ABC oh my god!!' >>> line.find("o") 16 >>> line.index("o") 16 它们总是返回相同的结果。 谢谢 未找到子字符串时返回-1 >>> line = 'hi, this is ABC oh my god!!' >>> line.find('?'

我是python新手,不能完全理解find和index之间的区别

>>> line
'hi, this is ABC oh my god!!'
>>> line.find("o")
16
>>> line.index("o")
16
它们总是返回相同的结果。 谢谢

未找到子字符串时返回
-1

>>> line = 'hi, this is ABC oh my god!!'
>>> line.find('?')
-1
当引发
值错误时

>>> line.index('?')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>行索引('?'))
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ValueError:未找到子字符串

如果找到子字符串,这两个函数的行为方式相同

另外,“查找”仅适用于列表、元组和字符串的as索引可用的字符串

>>> somelist
['Ok', "let's", 'try', 'this', 'out']
>>> type(somelist)
<class 'list'>

>>> somelist.index("try")
2

>>> somelist.find("try")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'find'

>>> sometuple
('Ok', "let's", 'try', 'this', 'out')
>>> type(sometuple)
<class 'tuple'>

>>> sometuple.index("try")
2

>>> sometuple.find("try")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'find'

>>> somelist2
"Ok let's try this"
>>> type(somelist2)
<class 'str'>

>>> somelist2.index("try")
9
>>> somelist2.find("try")
9

>>> somelist2.find("t")
5
>>> somelist2.index("t")
5
>>somelist
[“好”、“让我们”、“试试”、“这个”、“出去”]
>>>类型(somelist)
>>>somelist.index(“try”)
2.
>>>somelist.find(“try”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:“列表”对象没有“查找”属性
>>>某元组
(‘好’、‘让我们’、‘试试’、‘这个’、‘出去’)
>>>类型(sometuple)
>>>sometuple.index(“try”)
2.
>>>sometuple.find(“try”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:“tuple”对象没有属性“find”
>>>某物清单2
“好的,让我们试试这个”
>>>类型(somelist2)
>>>somelist2.索引(“try”)
9
>>>somelist2.find(“try”)
9
>>>somelist2.find(“t”)
5.
>>>somelist2.索引(“t”)
5.

@falsetru解释了函数之间的差异,我对它们进行了性能测试

"""Performance tests of 'find' and 'index' functions.

Results:
using_index t = 0.0259 sec
using_index t = 0.0290 sec
using_index t = 0.6851 sec

using_find t = 0.0301 sec
using_find t = 0.0282 sec
using_find t = 0.6875 sec

Summary:
    Both (find and index) functions have the same performance.
"""


def using_index(text: str, find: str) -> str:
    """Returns index position if found otherwise raises ValueError."""
    return text.index(find)


def using_find(text: str, find: str) -> str:
    """Returns index position if found otherwise -1."""
    return text.find(find)


if __name__ == "__main__":
    from timeit import timeit

    texts = [
        "short text to search" * 10,
        "long text to search" * 10000,
        "long_text_with_find_at_the_end" * 10000 + " to long",
    ]

    for f in [using_index, using_find]:
        for text in texts:
            t = timeit(stmt="f(text, ' ')", number=10000, globals=globals())
            print(f"{f.__name__} {t = :.4f} sec")
        print()

如果找到一个子字符串,两个函数的行为都是一样的?@user1603970,是的,它们是这样的。它们的参数也是相同的。@user1603970,根据我在答案中链接的
索引
文档:Like find(),但在找不到子字符串时引发ValueError。正如@reep提到的,find仅适用于as index可用于列表的字符串,tuple和stringspython应该删除这两个方法之一。其中一个很好地发挥了作用。另外,我认为
index
返回
-1
find
返回
ValueError
更合适,以防未找到
sub