Python: (sub) String Equivalence vs Membership Quick Test List

Can someone explain the following to me (python 2.7)

Two string numbers from the analyzed file:

'410.9' '410.9' (Note the end space)

A_LIST = ['410.9 '] '410.9' in '410.9 ' True '410.9' in A_LIST False 

There is no problem with this - just try to understand why this is so.

Thanks!

+4
source share
3 answers

This is the correct behavior because:

  >>>'410.9'=='410.9 ' >>>False 

and when you write down the list for membership in a specific element, you are actually doing something like this:

 ... for item in A_LIST: if item == '410.9': return True ... 
+4
source

in with two string checks or a substring, while in with a list checks for ownership.

What you want is something like [x for x in A_LIST if '419' in x]

+7
source

The first test checks whether the first line is a substring of the second, and the second test checks whether the line is a member of this list. Since it is not exactly equal to any member of the list, the second test returns false.

+5
source

All Articles