Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python startswith work?

Tags:

python

string

I am not able to understand the behavior of the str.startswith method.

If I execute "hello".startswith("") it returns True. Ideally it doesn't starts with empty string.

>>> "hello".startswith("")
True

The documentation states:

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

So how does the function work?

like image 897
user1211 Avatar asked Aug 26 '26 01:08

user1211


2 Answers

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.

like image 82
Martijn Pieters Avatar answered Aug 27 '26 15:08

Martijn Pieters


A string p is a prefix of a string s if s = p + x, so the empty string is a prefix of all strings (it's like 0, s = 0 + s).

like image 37
Kirill Bulygin Avatar answered Aug 27 '26 15:08

Kirill Bulygin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!