简体   繁体   English

防止“if”python中的部分字符串匹配)

[英]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.我正在测试mystring是否在mylist ,它工作正常。

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 .并且我正在测试 if 语句,我希望它仅在匹配准确时才通过,即mystring应该通过并仅对apples do something with mystring ,而不是appapple The problem is that partial matches of mystring to mylist are passing.问题是mystringmylist部分匹配正在通过。

Ie in the example above if mystring is app it's passing and I don't want it too.即在上面的示例中,如果mystringapp它正在传递而我也不想要它。 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 :只需使用相等运算符而不是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.运算符“in”可以在序列中找到一个项目,但它对字符串的行为有所不同 - 从 ePython 2.3 IIRC 开始 - 当序列是字符串(或 unicode)时,它也将匹配子字符串。

So if you just wnat to check if a word is inisde a list, in is ok - as in所以,如果你只是wnat检查一个词是inisde列表, 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因此,代替if any (mystring in s for s in mylist)只做if mystring in mylist

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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