How good is startswith?

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

    Yes: it’s easier to use and easier to read. When you are testing for more than one letter, when using slicing, you’ll have to know how long the target text is:

    haystack = 'Hello, World!'
    needle = 'Hello'
    
    # The easy way
    result = haystack.startswith(needle)
    
    # The slightly harder way
    result = haystack[:len(needle)] == needle
    

    Edit: The question seems to have changed. It now says, “knowing text is not empty and we are only interested in the first character of it.” That turns it into a fairly meaningless hypothetical situation.

    I suspect the questioner is trying to “optimize” his/her code for execution speed. If that is the case, my answer is: don’t. Use whichever form is more readable and, therefore, more maintainable when you have to come back and work on it a year from now. Only optimize if profiling shows that line of code to be the bottleneck. This is not some O(n²) algorithm. It’s a string comparison.

提交回复
热议问题