Rahul Rahul - 7 months ago 22
Python Question

Matching whole words using "in" in python

I've been searching around for some time for this, but have still not found an answer, maybe its got some thing to do with regular expressions, but i think there should be a simple answer that I am missing here. It seems very trivial to me ... here goes:

On the python interpreter I get:

"abc" in "abc123"

as True.

I want it a command that returns a False. I want the entire word to be matched.



If you want to do a plain match of just one word, use ==:

'abc' == 'abc123' # false

If you're doing 'abc' in ['cde','fdabc','abc123'], that returns False anyway:

'abc' in ['cde','fdabc','abc123'] # False

The reason 'abc' in 'abc123' returns true, from the docs:

For the Unicode and string types, x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1.

So for comparing against a single string, use '==', and if comparing in a collection of strings, in can be used (you could also do 'abc' in ['abc123'] - since the behaviour of in works as your intuition imagines when y is a list or collection of sorts.