find vs in operation in string python

前端 未结 3 838
無奈伤痛
無奈伤痛 2020-12-15 19:32

I need to find pattern into string and found that we can use in or find also. Could anyone suggest me which one will be better/fast on string. I need not to find index of pa

相关标签:
3条回答
  • 2020-12-15 19:49

    Use in , it is faster.

    dh@d:~$ python -m timeit 'temp = "1:5.9";temp.find(":")'
    10000000 loops, best of 3: 0.139 usec per loop
    dh@d:~$ python -m timeit 'temp = "1:5.9";":" in temp'
    10000000 loops, best of 3: 0.0412 usec per loop
    
    0 讨论(0)
  • 2020-12-15 19:49

    Definitely use in. It was made for this purpose, and it is faster.

    str.find() is not supposed to be used for tasks like this. It's used to find the index of a character in a string, not to check whether a character is in a string. Thus, it will be much slower.

    If you're working with much larger data, then you really want to be using in for maximum efficiency:

    $ python -m timeit -s "temp = '1'*10000 + ':' " "temp.find(':') == -1"
    100000 loops, best of 3: 9.73 usec per loop
    $ python -m timeit -s "temp = '1'*10000 + ':' " "':' not in temp"
    100000 loops, best of 3: 9.44 usec per loop
    

    It's also much more readable.

    Here's a documentation link about the keyword, and also a related question.

    0 讨论(0)
  • 2020-12-15 20:02

    Using in will be faster as using in provides only pattern while if you use find it will give you pattern as well as its index so it will take some extra time in computing the index of the string as compared to in. However if you are not dealing with large data then it dosent matter what you use.

    0 讨论(0)
提交回复
热议问题