It's not often I come across something in Python that surprises me. Especially in something as mundane as string operations, but I guess Python still has a trick or two up its sleeve.
Have a look at this string:
>>> s = "A"
How many possible sub-strings are in
s? To put it another away, how many values of
x are there where the expression
x in s is true?
Turns out it is 2.
>>> "A" in s True >>> "" in s True
The empty string is in the string
"A". In fact, it's in all the strings.
>>> "" in "foo" True >>> "" in "" True >>> "" in "here" True
Turns out the empty string has been hiding every where in my code.
Not a complaint, I'm sure the rationale is completely sound. And it turned out to be quite useful. I had a couple of lines of code that looked something like this:
if character in ('', '\n'): do_something(character)
In essence I wanted to know if
character was an empty string or a newline. But knowing the empty string thang, I can replace it with this:
if character in '\n': do_something(character)
Which has exactly the same effect, but I suspect is a few nanoseconds faster.
Don't knock it. When you look after the nanoseconds, the microseconds look after themselves.