Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
943 views
in Technique[技术] by (71.8m points)

string - How does python startswith work?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...