Is
text.startswith(\'a\')
better than
text[0]==\'a\'
?
Knowing text is not empty and we a
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.
PEP 8 explicitly tells to use startswith, because of readability:
- Use ''.startswith() and ''.endswith() instead of stringslicing 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':
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.
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