How good is startswith?

前端 未结 10 446
执笔经年
执笔经年 2021-01-07 19:38

Is

text.startswith(\'a\')  

better than

text[0]==\'a\'  

?

Knowing text is not empty and we a

相关标签:
10条回答
  • 2021-01-07 19:52

    text[0] can fail but the equivalent text[:1] is safe if the string is empty.

    If you want to compare more than one characters, I believe .startswith() is better.

    0 讨论(0)
  • 2021-01-07 19:55

    PEP 8 explicitly tells to use startswith, because of readability:

    - Use ''.startswith() and ''.endswith() instead of string
    

    slicing to check for prefixes or suffixes.

      startswith() and endswith() are cleaner and less error prone.  For
      example:
    
        Yes: if foo.startswith('bar'):
    
        No:  if foo[:3] == 'bar':
    
    0 讨论(0)
  • 2021-01-07 19:58

    I'd agree with the others that startswith is more readable, and you should use that. That said, if performance is a big issue for such a special case, benchmark it:

    $ python -m timeit -s 'text="foo"' 'text.startswith("a")'
    1000000 loops, best of 3: 0.537 usec per loop
    
    $ python -m timeit -s 'text="foo"' 'text[0]=="a"'
    1000000 loops, best of 3: 0.22 usec per loop
    

    So text[0] is amost 2.5 times as fast - but it's a pretty quick operation; you'd save ~0.3 microseconds per compare depending on the system. Unless you're doing millions of comparisons in a time critical situation though, I'd still go with the more readable startswith.

    0 讨论(0)
  • 2021-01-07 19:58

    Personally I would say startswith is more readable.

    Also, from Python 2.5 startwith can take a tuple of prefixes to look for:

    >>> "hello world".startswith(("hello","goodbye"))
    True
    
    0 讨论(0)
提交回复
热议问题