Here is how I check whether mystring begins with some string:
>>> mystring.lower().startswith("he")
True
The problem is that mystring is very long (thousands of characters), so the lower() operation takes a lot of time.
QUESTION: Is there a more efficient way?
My unsuccessful attempt:
>>> import re;
>>> mystring.startswith("he", re.I)
False
You could use a regular expression as follows:
On a 2000-character string this is about 20x times faster than
lower():If you are matching the same prefix repeatedly, pre-compiling the regex can make a large difference:
For short prefixes, slicing the prefix out of the string before converting it to lowercase could be even faster:
Relative timings of these approaches will of course depend on the length of the prefix. On my machine the breakeven point seems to be about six characters, which is when the pre-compiled regex becomes the fastest method.
In my experiments, checking every character separately could be even faster:
However, this method only works for prefixes that are known when you’re writing the code, and doesn’t lend itself to longer prefixes.