简体   繁体   中英

Preventing partial string match in "if" python)

I am sure this is simple but I can't see or possibly can't understand the solution.

I have some code:

if any (mystring in s for s in mylist)
     do something with mystring

where I'm testing to see if mystring is in mylist , which works fine.

However if I have the list

['apples','pears','chickens']

and I am testing the if statement, I want it to only pass if the match is exact, ie mystring should pass and do something with mystring only with apples , not app or apple . The problem is that partial matches of mystring to mylist are passing.

Ie in the example above if mystring is app it's passing and I don't want it too. I know this is trivial, so sorry about that.

I think you should just do

if mystring in mylist:
  do something with mystring

If you just want to test whether they are equal, you can do just that:

if any (mystring == s for s in mylist):
     do something with mystring

But then you could simplify it to just checking whether your string is in the list like this:

if mystring in mylist:
     do something with mystring

Just use the equality operator instead of in :

if any (mystring == s for s in mylist)
     do something with mystring

The operator "in" can find an item in a sequence, but it behaves differently for strings - sinc ePython 2.3 IIRC - when teh sequence is a string (or unicode), it will also match substrigns.

So if you just wnat to check if a word is inisde a list, in is ok - as in

if "apple" in ["apple", "pear", "berry"]:

So, instead of if any (mystring in s for s in mylist) do just if mystring in mylist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM