I know that if we would like to know whether string
a is contained in
b we can use:
a in b
When a equals to b, the above express still returns
True. I would like an expression that would return
a == b and return
a is a substring of
b. So I used the following expression:
a in b and a != b
I just wonder is there a simpler expression in Python that works in the same way?
This is going to be a short answer, but it is what it is. What you have is enough.
While there might be other alternatives, the way you did it is easy enough to understand, simple and more readable than anything else (of course this is subjective to each and everyone). IMO a simpler expression in Python that works in the same way doesn’t exist. That’s just my personal perspective on this subject. I’m usually encouraged to follow KISS:
The KISS principle states that most systems work best if they are kept
simple rather than made complicated; therefore simplicity should be a
key goal in design and unnecessary complexity should be avoided.
As an example, the other answer it’s not any different from the explicit
and, and the chaining can be confusing when used with
== because many people will see that as
(a1 in b) != a1, at least at first glance.
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
Likes the other answers it’s also O(n), but the length operation should be O(1). It should also be better suited for edge cases (e.g. a being bigger than b)
b.find(a) > 0 or b.startswith(a) and len(b) > len(a)
I’m not saying this is the best answer. It’s just another solution. The OP’s statement is as good as any. The accepted answer is also good. But this one does work and demonstrates a different approach to the problem.