How does python startswith work?

str.startswith() can be expressed in Python code as:

 def startswith(source, prefix):
    return source[:len(prefix)] == prefix

It tests if the first len(prefix) characters of the source string are equal to the prefix. If you pass in a prefix of length zero, that means the first 0 characters are tested. A string of length 0 is always equal to any other string of length 0.

Note that this applies to other string tests too:

>>> s="foobar"
>>> '' in s
True
>>> s.endswith('')
True
>>> s.find('')
0
>>> s.index('')
0
>>> s.count('')
7
>>> s.replace('', ' -> ')
' -> f -> o -> o -> b -> a -> r -> '

Those last two demos, counting the empty string or replacing the empty string with something else, shows that you can find an empty string at every position in the input string.

Leave a Comment