How can I check if string a is a substring but not equal to string b?

I know that if we want to know if a string is contained a

in b

, we can use:

a in b

      

When a is equal to b, the above express still returns True

. I would like an expression that will return False

when a == b

and return True

when a

is a substring b

. So I used the following expression:

a in b and a != b

      

I'm just wondering if there is a simpler expression in Python that works the same?

+3


source to share


2 answers


Not sure how efficient direct string comparisons are in Python, but assuming they are O (n), this should be reasonably efficient and still readable:

len(a) < len(b) and a in b

      



Strikes other answers, also O (n), but the length operation should be O (1). It should also be better suited for edge cases (e.g. size larger than b)

+4


source


This will be a short answer, but it is what it is. You have enough.

While there may be other alternatives, the way you did it is easier enough to understand, simpler and more readable than anything else (of course, this is subjective to each and every one). IMO a simpler expression in Python that works the same doesn't exist. This is just my personal perspective on this topic. I am generally advised to follow KISS :



The KISS principle states that most systems work best if they are kept simple rather than complex; therefore simplicity should be to be avoided as a key design goal and unnecessary complexity.

As an example, the other answer is no different from the explicit one and

, and chaining can be confusing when used with in

and ==

, because many people will see it as (a1 in b) != a1

, at least at first glance.

+1


source







All Articles