find vs in operation in string python

前端 未结 3 851
無奈伤痛
無奈伤痛 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

    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.

提交回复
热议问题