-1

I am trying to figure out a string problem in Python. So this is from the online course Building A Search Engine and in the quiz there is a problem:

For any string s = '<any string>', which of the following always has value 0?

  • (a) s.find(s)
  • (b) s.find('s')
  • (c) 's'.find('s')
  • (d) s.find('')
  • (e) s.find(s+'!!!')+1

Answer: (a), (c), (d) & (e)

And I am pretty sure about other choices except for choice (d).

I think the output should be -1 but the output is 0.

output

So my reasoning follows:

s is the predefined question before but '' should be considered as an empty string. So in a string to find an empty string, why not the returning is not -1 because you can not find empty in any string.

==============================================

OK, I can see my wrong thinking.

In the documentation,

Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

2
  • An empty string is a subset of any string, just like an empty set is a subset of any set. Moreover, any string starts with an empty string. That's why. Commented Jan 19, 2018 at 23:54
  • "you can not find empty in any string" Of course you can. You can find it literally everywhere. Commented Jan 19, 2018 at 23:55

1 Answer 1

2

As string.find(s, sub[, start[, end]]) document says:

Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end].

The way Python interpreter performs the search is by looking for your substring from the start index of the string and going till the end index.

It iterates and compares your substring as:

your_string[i:i+len(substring)]
# where `i` is the index

for your case, your substring is having 0 length, and with string slicing with 0th index at end, it returned empty string. For example:

>>> your_string = 'abcd'
>>> your_string[0:0]
''

Hence, when you executed str.find with empty string on it, you got the result as 0

>>> your_string.find('')
0

# Because your_string[0:0] == ''
#                     ^  this being the index returned
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the classifying. Now I see, find works with the loop of the string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.