简体   繁体   English

查找模式是否在两个字符串中的任何一个中的最短方法

[英]Shortest way to find if a pattern is in any of two strings

I have a pattern that I need to know (by returning a boolean ) if is contained in any of two strings, and I want to know how to do this in the shortest way possible. 我有一个模式,我需要知道(通过返回boolean )两个字符串中的任何一个是否包含,并且我想知道如何以最短的方式进行操作。

I know I can use any() for larger amounts of strings but I was looking for the shortest way to accomplish this for string pairs , because using any() would require list comprehension at the very least. 我知道我可以对any()数量的字符串使用any() ,但是我正在寻找对字符串完成此操作的最短方法,因为使用any()至少需要列表理解。

I was expecting something like this, but it does not work: 我期待这样的事情,但它不起作用:

pattern in (string1 or string2)

I was getting confused because this code actually works for string1 , but it only checks string2 if string1 is False or None (I think). 我很困惑,因为此代码实际上适用于string1 ,但是它仅检查string2string1False还是None (我认为)。

Ultimately I can use any((pattern in s for s in (string1, string2))) , but it's less pretty or readable inside the code. 最终,我可以使用any((pattern in s for s in (string1, string2))) ,但是它在代码内部不太美观可读性强

I think there's no nitpicks. 我认为没有子。 Just do the most intuitive: 只要做到最直观:

has_pattern = pattern in string1 or pattern in string2

Note that (string1 or string2) is almost always wrong by your intention, as the result of that expression is string1 if it's non-empty, and string2 otherwise. 请注意, (string1 or string2)几乎总是出于您的意图而出错,因为该表达式的结果为string1如果非空),否则为string2

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

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