简体   繁体   English

使用 IF 条件在 python 中搜索字符串时,哪个默认变量存储子字符串?

[英]Which default variable stores the substring while searching for string in python using IF condition?

if "a" or "b" or "c" in x:
    print (x)
    print ("a" or "b" or "c")

Here I want to print the substring a or b or c which present in the string and want to do some manipulation on it.在这里,我想打印出现在字符串中的子字符串 a 或 b 或 c 并希望对其进行一些操作。 So which variable stores the substring?那么哪个变量存储子字符串呢?

There is no variable which gets populated under the hood when you find a match.当您找到匹配项时,没有任何变量会在引擎盖下填充。 If you need the match index or the matched substring, you need to ask for it specifically.如果需要匹配索引或匹配的子字符串,则需要专门询问。

In any event, "a" or "b" or "c" in x doesn't do what you hope or assume.无论如何, "a" or "b" or "c" in x中的"a" or "b" or "c" in x并不符合您的希望或假设。 It checks if "a" is a non- False value (which it is, so the remainder of the alternatives are skipped; but for the record, it would then check if "b" is a non- False value, and then finally if "c" in x returns a non- False value).它检查"a"是否为非False值(确实如此,因此跳过其余的替代值;但对于记录,它将检查"b"是否为非False值,然后最后如果"c" in x返回非False值)。

Depending on what exactly you are looking for, perhaps a regular expression would solve your problem?根据您正在寻找的内容,也许正则表达式可以解决您的问题?

import re
regex = re.compile(r'a|b|c')
match = regex.search(x)
if match:
    print('{0} in {1}'.format(match.group(0), x))

The precise behavior might differ from what you desire.确切的行为可能与您想要的不同。 This will find the leftmost match on any one of the alternatives in the regular expression.这将在正则表达式中的任何一个替代项上找到最左边的匹配项。 If you want different behavior (perhaps first check if "a" is anywhere in the string?) then perhaps ask a more well-defined question.如果您想要不同的行为(也许首先检查"a"是否在字符串中的任何位置?)然后可能会问一个更明确的问题。

Wrong condition错误的条件

First of all "a" or "b" or "c" in x does not checks if any of those characters are in the string.首先, "a" or "b" or "c" in x中的"a" or "b" or "c" in x不检查这些字符中是否有任何一个在字符串中。 It checks the truthiness of each expression, immediately stopping at "a" which is truthy.它检查每个表达式的真实性,立即停在真实的"a"处。

Instead you want this condition:相反,你想要这个条件:

if 'a' in x or 'b' in x or 'c' in x:

It can also be written with any .它也可以用any .

if any(c in x for c in ('a', 'b', 'c')):

Finding the substring寻找子串

As for you question, neither of the above will keep track of which substring was found in x for the expression to be True .至于您的问题,上述两者都不会跟踪在x中找到哪个子字符串以使表达式为True You need to do that yourself.你需要自己做。

chars = ('a', 'b', 'c')
found_char = next((c for c in chars if c in x), False)
if found_char:
    ...

I don't fully understand but, the efficient-est way (at least i think is):我不完全理解,但是,最有效的方式(至少我认为是):

if any(i in x for i in {'a', 'b', 'c']):
    print ("a" or "b" or "c")

But to get it do:但要做到这一点:

if any(i in x for i in {'a', 'b', 'c'}):
    print ([i for i in {'a', 'b', 'c'} if i in x])

You can't check three substrings like this.你不能像这样检查三个子字符串。 Here if condition is becoming if ("a") or ("b") or ("c" in x) , "a" is True hence will always pass the if condition.这里 if 条件变成if ("a") or ("b") or ("c" in x) ,"a" 为 True 因此将始终通过 if 条件。

You can the if condition to:您可以使用 if 条件:

if "a" in x or "b" in x or "c" in x

Try using a regex for this kind of thing.尝试对这种事情使用正则表达式。

>>> import re
>>> re.findall('[abc]', 'foobaz')
['b', 'a']

Note that the expression "a" or "b" or "c" in x is just 'a' .请注意, "a" or "b" or "c" in x中的表达式"a" or "b" or "c" in x只是'a'

Based on the English interpretation of your code, it looks like you want something like this:根据您的代码的英文解释,您似乎想要这样的东西:

for val in ["a", "b", "c"]:
    if val in x:
        print(x)
        print(val)
        break  # stop checking once the first match is found

Olivier Melançon's answer achieves the same thing, so the choice between that and this would just be a matter of style. Olivier Melançon 的回答达到了同样的目的,所以在这和这之间的选择只是风格问题。

If you want all the matches, you could use the set intersection operator ( & ):如果您想要所有匹配项,您可以使用设置交集运算符( & ):

matches = {"a", "b", "c"} & set(x)
print(matches)

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

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