【问题标题】:difference between find and index查找和索引之间的区别
【发布时间】:2014-04-07 01:22:14
【问题描述】:

我是 python 新手,不太了解 find 和 index 之间的区别。

>>> line
'hi, this is ABC oh my god!!'
>>> line.find("o")
16
>>> line.index("o")
16

它们总是返回相同的结果。 谢谢!!

【问题讨论】:

    标签: python string python-2.7


    【解决方案1】:

    @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()
    

    【讨论】:

      【解决方案2】:

      find 也只适用于字符串,因为 index 可用于列表、元组和字符串

      >>> 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
      

      【讨论】:

        【解决方案3】:

        str.find 在找不到子字符串时返回-1

        >>> line = 'hi, this is ABC oh my god!!'
        >>> line.find('?')
        -1
        

        虽然str.index 引发ValueError

        >>> line.index('?')
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        ValueError: substring not found
        

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

        【讨论】:

        • 如果找到子字符串,这两个函数的行为方式相同吗?
        • @user1603970,是的,他们这样做了。它们的参数也一样。
        • @user1603970,根据我在答案中链接的index 文档:类似于 find(),但在找不到子字符串时引发 ValueError。
        • 正如@reep 提到的,find 仅适用于字符串,其中索引可用于列表、元组和字符串
        • python 应该放弃这两种方法之一。其中之一很好地达到了目的。另外我认为index 更适合返回-1find 返回ValueError,以防sub 找不到。
        猜你喜欢
        • 2010-10-03
        • 2010-11-11
        • 2018-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-14
        • 2014-08-27
        • 1970-01-01
        相关资源
        最近更新 更多