Why does Python consider an empty string ('or "") to be present in a simple variable with characters, but not in a composite one?

Asked

Viewed 540 times

2

When doing basic programs asking for user input, and testing if it is empty with in because of another variable that defines possible inputs, I come across the following:

if '' in 'abc':
    print('not ok')
else:
    print('ok')

>>> not ok

and:

if '' in ['abc'] or '' in ('abc',) or '' in {'abc'}:
    print('not ok')
else:
    print('ok')

>>> ok

If ''/"" is present in strings in simple variables, why is it not present in strings in compound variables, or vice versa? What is the difference? Is there any explanation for this?

Link to another related question (in English), with complete answers for those who have more questions.

1 answer

4


This behavior can be found in documentation:

For container types such as list, tuple, set, frozenset, Dict, or Collections.deque, the Expression x in y is equivalent to any(x is e or x == e for e in y).

That is, translating, for data collections the expression x in y is equivalent to checking x equality with each element of the y collection. If any of them returns true, then x in y returns true.

For strings, on the same link we can check:

For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are Always considered to be a substring of any other string, so "" in "abc" will Return True.

Translating, x in y where y is a string we have the true return if and only if x is a sub-string of y. The documentation also says that an empty string will always be considered to be contained in another string.

One empty string is mathematically considered substring of any other string because it is the neutral element of concatenation.

If you ask me:

There’s a way to fit that Empty String in some other string to form the string "ABCDE"?

the answer will be yes:

"" + "ABCDE" = "ABCDE"

which by definition leads to the conclusion that "" in "ABCDE" must return true.

Related response link (in English)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.