How good is startswith?

前端 未结 10 490
执笔经年
执笔经年 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: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':
    

提交回复
热议问题